Ruby Hash coolness September 28th, 2009
Don’t shoot me if you already use this every day, but this is new to me.
In the past I’ve often had code like this
@hosts = {} @accounts.each do |account| @hosts[account[:host]] ||= [] @hosts[account[:host]] << account end
But why do this hen you can just add some initializer code to your hash.
@hosts = Hash.new { |h, k| h[k] = [] } @accounts.each do |account| @hosts[account[:host]] << account end
Where Hash automatically invokes the block when an unknown hash key is called. Great!
l
Seems to be the same as Hash.new([]) ;)
@grosser: It most definitely is not the same thing as Hash.new([]). When you do that, every value will share the exact same Array object. That means if you did: hash[:foo] << 1; hash[:bar] << 2, and then looked at hash[:foo] you’d get [ 1, 2 ]. Same thing if you looked at hash[:bar]. Modifying either of those will also affect the other.