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
=> nil
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.
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.
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.