Today I Learned

hashrocket A Hashrocket project

Random post about #ruby surprise

Setting Struct properties with an index

It's rare that I get a chance to use structs but yesterday while parsing some xml (!!!) I wrote an algorythm where it would be handy to set values of a struct with an incrementing number rather than a symbol.

Low and Behold! Ruby Structs allow you to set attributes with either the name of the property or the ordinal with which it was declared.

2.5.0 :001 > Apple = Struct.new(:color, :size)
 => Apple
2.5.0 :002 > apple = Apple.new
 => #<struct Apple color=nil, size=nil>
2.5.0 :003 > apple[0] = 'red'
 => "red"
2.5.0 :004 > apple[1] = 'huge'
 => "huge"
2.5.0 :005 > apple
 => #<struct Apple color="red", size="huge">
Ruby

Structs are a great data structure that I'm going to try to use more in my daily programming.