Reputation: 2960
I have an array: user = {"name" => "Tom", "address" => "Spain"}
I want to add to this a new attribute: user << {"age" => 26}
I get this error: undefined method '<<' for {"name"=>"Tom", "address"=>"Spain"}:Hash
How should I add a new value for this element?
Upvotes: 1
Views: 598
Reputation: 17834
You can add key value pair this way
user["age"] = 26 # => {"name"=>"Tom", "address"=>"Spain", "age"=>26}
or you can use merge
user.merge("age" => 26) # => {"name"=>"Tom", "address"=>"Spain", "age"=>26}
Upvotes: 3
Reputation: 441
Since Ruby hashes aren't ordered, appending to them with << doesn't make sense.
However, you can use
user["age"] = 26
to the same effect.
Upvotes: 0