Project Ramon

A learning journey from a Ruby noob perspective

A Brief intro to Ruby Struct

struct_header_img

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 attr_accessor.

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 do and 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:

struct_img1

There is a very informative blog post by Steve Klabnik that covers Struct and 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.

Advertisements

Categories: Ruby

Tags: ,

1 reply

Trackbacks

  1. Write Ruby that Embraces Change | Project Ramon

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s