nistvan
nistvan

Reputation: 2960

Add key-value pair to a hash in Ruby

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

Answers (2)

Rajdeep Singh
Rajdeep Singh

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

mkis
mkis

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

Related Questions