Literate Programming

Meta

Table of Contents

Random Ruby Tricks: Struct.new

1 September 2012

One of my favorite classes in Ruby is Struct, but I feel like many Rubyists
don't know when to take advantage of it. The standard library has a lot of
junk in it, but Struct and OStruct are super awesome.

Now. We have these two birthdays. In this case, we know about why the test was
failing, but imagine this failure in a real codebase. Are these month/day/year
or day/month/year? You can't tell, it could be either. If we switched our code
to this:

We have a way, way more clear failure. We can clearly see that its our days
that are off.

Of course, there are other good reasons to package related instance variables
into Structs, too: it makes more conceptual sense. This code represents our
intent better: a Person has a Birthday, they don't have three unrelated numbers
stored inside them somehow. If we need to add something to our concept of
birthdays, we now have a place to put it.