Nice. You can also give Struct.new a block and define instance methods:
irb(main):002:0> Struct.new('Foo', :bar) do
irb(main):003:1* def baz; :omg; end
Thanks! Super neat. :)
I’ve been using Struct.new as a superclass for a while, but today I hit a bit of a gotchya that is worth being aware of.
1.9.3p194 :001 > class Person < Struct.new(:first, :last); end
1.9.3p194 :002 > Array(Person.new('Joe', 'Bloggs'))
=> ["Joe", "Bloggs"]
Struct actually implements to_a, returning the list of values as an array. So if you pass instances of your subclass to Array() you’ll get the list of values, not the instance wrapped in an Array, which is probably what you expected.
There are some really annoying problems with OpenStruct that I found while rewriting it. For instance:
I am oddly very excited about this – especially around the clarity for tests. That birthday example was beautiful.
I am very excited about this – especially around the clarity for tests. That birthday example was beautiful.