A Ruby Struct is a super quick way to bundle a list of attributes together without having to write out an explicit class. Struct does this by generating a new subclass and creating accessor methods (i.e. read/write) automatically, as if we had used the method
Here is an example:
So here’s whats happening. On
line:1 instead of writing our normal
class Ticket declaration, we created a Struct subclass by using
Struct.new. The arguments are then entered as symbols and Ruby creates reader and writer methods for each of them, as if we had done the following:
Which is Ruby sugar for declaring reader and writer methods like so:
Next we add a code-block to the
Ticket subclass of
Struct as we can see on
line:1 and line:21 in our first illustration. Inside of the
end blocks we define our instance methods like we would if writing out a typical class declaration.
And to get the program to work, we just create a
Ticket object with some values, and then have our new object call our
payment instance method to get the program started.
Check it out:
There is a very informative blog post by Steve Klabnik that covers
OStruct in a way I could understand easily. If you’re interested in shortening your time when you’re in a sandbox environment, or are looking to make some of your domain concepts into concrete simple classes, check out his post.
And while we’re at it, have a peak at the Ruby docs also.