Search code examples
rubyhashblock

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

Solution

  • 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