h = Hash.new { |h,k| h[k] = [] }
h['foo'] << "a"
h['bar'].push "b"
puts h.inspect
outputs {"foo"=>["a"], "bar"=>["b"]}
. In other words, we declare a hash with a constructor that sets each new key to have a value of a empty array. Otherwise, we would have to test each hash key to see if it was already initialized to an array, if not initialized we'd set that hash key's value to an empty array. It's a common thing to do, but Ruby makes it easy and automagic.
I suppose in perl you can rely on auto vivification.
But as you can imagine the Ruby idiom can be generalized to more complicated initializations.
push @{$h{'foo'}}, "a";
No comments:
Post a Comment