简体   繁体   中英

Create hash using block (Ruby)

Can I create a Ruby Hash from a block?

Something like this (although this specifically isn't working):

foo = Hash.new do |f|
  f[:apple] = "red"
  f[:orange] = "orange"
  f[:grape] = "purple"
end

In Ruby 1.9 (or with ActiveSupport loaded, eg in Rails), you can use Object#tap , eg:

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.

I cannot understand why

foo = {
  :apple => "red",
  :orange => "orange",
  :grape => "purple"
}

is not working for you?

I wanted to post this as comment but i couldn't find the button, sorry

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"
end
foo.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 .

What's wrong with

foo = {
  apple:  'red',
  orange: 'orange',
  grape:  'purple'
}

As others have mentioned, simple hash syntax may get you what you want.

# Standard hash
foo = {
  :apple => "red",
  :orange => "orange",
  :grape => "purple"
}

But if you use the "tap" or Hash with a block method, you gain some extra flexibility if you need. What if we don't want to add an item to the apple location due to some condition? We can now do something like the following:

# Tap or Block way...
foo = {}.tap do |hsh|
  hsh[:apple] = "red" if have_a_red_apple?
  hsh[:orange] = "orange" if have_an_orange?
  hsh[:grape] = "purple" if we_want_to_make_wine?
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM