Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create hash using block (Ruby)

Tags:

ruby

hash

block

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
like image 510
user94154 Avatar asked Sep 08 '10 16:09

user94154


1 Answers

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?
}
like image 135
Ondecko Avatar answered Oct 14 '22 20:10

Ondecko