Why isn't the Hash.new method working the same as the curly brace method?



why is this code printing the ‘name’ key as an array and not like the other keys?

things = Hash.new
things['name'] = 'name',
things['age'] = 'age',
things['hungry?'] = false
puts things

{“age”=>“age”, “hungry?”=>false, “name”=>[“name”, “age”, false]}

But this code prints the key/value pairs correctly.

my_hash = { "name" => "Eric",
  "age" => 26,
  "hungry?" => true
puts my_hash

{“name”=>“Eric”, “age”=>26, “hungry?”=>true}

Is this a defect with the lesson or am I missing something here? The lesson is leading me to believe that either method produces the same results but it looks like you can’t use Hash.new to create hashes with multiple key/value pairs.


The bug is in your code. You have commas following name so all the values are assigned. Remove the commas and all is as expected.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.