Bastian
Bastian

Reputation: 207

why am I not able to merge hashes within an each loop

Iam trying to loop through an array and merge one key/value pair to my hashes within this array, however it is not working. When I do it manually, it is working. What am I doing wrong?

:001 > array = [{foo: 5}, {bar: 3}]
 => [{:foo=>5}, {:bar=>3}] 
:002 > array.each{|hash| hash.merge(match: true)}
 => [{:foo=>5}, {:bar=>3}] 
:003 > array[0].merge(match: true)
 => {:foo=>5, :match=>true}

Upvotes: 1

Views: 255

Answers (2)

jan.zikan
jan.zikan

Reputation: 1316

@demir's answer is right.

If you don't want to change the original array. You can use map instead of each and assign the output to new variable.

array = [{ foo: 5}, { bar: 3 }]
new_array = array.map { |hsh| hsh.merge(match: true) }

Upvotes: 0

demir
demir

Reputation: 4709

Use merge! instead of merge. merge method returns a new hash, merge! adds the key value pairs to the hash.

array = [{ foo: 5 }, { bar: 3 }]
array.each { |hash| hash.merge!(match: true) }

Upvotes: 3

Related Questions