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!

tags: l 76 comments »