Create hash using block (Ruby)
In Ruby 1.9 (or with ActiveSupport loaded, e.g. in Rails), you can use Object#tap
, e.g.:
foo = Hash.new.tap do |bar| bar[:baz] = 'qux'end
You can pass a block to Hash.new
, but that serves to define default values:
foo = Hash.new { |hsh, key| hsh[key] = 'baz qux' }foo[:bar] #=> 'baz qux'
For what it's worth, I am assuming that you have a larger purpose in mind with this block stuff. The syntax { :foo => 'bar', :baz => 'qux' }
may be all you really need.
Passing a block to Hash.new
specifies what happens when you ask for a non-existent key.
foo = Hash.new do |f| f[:apple] = "red" f[:orange] = "orange" f[:grape] = "purple"endfoo.inspect # => {}foo[:nosuchvalue] # => "purple"foo # => {:apple=>"red", :orange=>"orange", :grape=>"purple"}
As looking up a non-existent key will over-write any existing data for :apple
, :orange
and :grape
, you don't want this to happen.
Here's the link to the Hash.new specification.