Programming with Soulcutter

Write code like you mean it

Default Hash Values (the RIGHT Way)

In my recent post about default hash values I was posting something I thought was pretty basic, and embarassingly I missed what should have been obvious. Right there in the documentation for Hash is the best way to initialize Hash keys on-demand:

1
2
3
4
options = Hash.new {|hash, key| hash[key] = [] } # => {}
options[:key] # => []
options[:key] << 'thing' # => ["thing"]
options # => {:key=>["thing"]}

I know I must've seen this before, but I guess it never stuck with me. Thanks to @alindeman, @pete_higgins, and @samphippen for straightening me out.

Is it better to be thought a fool than to open your mouth and remove all doubt? I dunno, but this fool learned the RIGHT answer to the problem as well as a dose of humility. I suppose that's worth something!

Comments