Ruby Notes - Structs
I recently learned about Structs while working my way through Pragmatic Studio’s Ruby Programming course, which I highly recommend btw. If you’re a beginner like me it will apply your basic Ruby knowledge to a project and teach you some new things along the way…like Structs.
What Are Structs
Structs are simply a collection of attributes, meaning they only have state, whereas Classes have both attributes and methods (state and behavior). To illustrate imagine we have a library class containing a bunch of book objects (its state) that you can check out and do other things to (its behavior). This type of object, since it has state and behavior warrants using a class.
1 2 3 4 5 6 7 8 9 |
|
Now, let’s assume the book objects the library class will contain won’t have any behavior i.e. they won’t have methods, they’ll simply have attributes such as: @title
, @author
, and @page_number
. We could create a book class like this:
1 2 3 4 5 6 7 8 9 |
|
OR since the book object has no methods we can use a Struct like so:
1 2 3 4 5 |
|
Using a Struct required far less code than writing out the book class ourselves and by calling .class
on Book we can see that Struct.new
actually went and generated the book class we made above for us…pretty cool huh!
Create Object Instances
With this Book class we can create as many new book objects as we want by calling Book.new
and passing it a title, author, and number of pages, like below:
1 2 3 4 5 6 7 8 |
|
This code instantiated 3 new book objects each with readable and writable attributes. One interesting thing about these book objects is they are actually Struct objects and therefore have some handy struct methods for accessing their attributes.
Accessing Attributes
In addition to the normal way of accessing class attributes you can also use the []
method to access attributes like you would from an array by inserting the index in the brackets or like you from a hash by inserting the key in the brackets. Here are some examples:
1 2 3 4 5 6 7 8 |
|
As you can see you can access the title
attribute by index or by name using a String or Symbol.
Learn More About Structs
- You can see more Struct methods by checking out the Struct Class doc.
- For a more comprehensive explination of Structs read the blog post Structs Inside and Out
- If you want to make Read-only Structs check out the Value Struct Gem and this blog post about it.