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
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?
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With