byCoder
byCoder

Reputation: 9184

How do I change a hash using new hash values?

I have these hashes:

{"a" => 1, "b" => 2, "c" => 3, "k" => 14}
{"b" => 51, "c" => 2, "d"  => 8}

I need to write code, so that after manipulation, the result would be:

{"a" => 1, "b" => 51, "c" => 2, "k" => 14}

I tried:

h1.each do |h, j|
  h2.each do |hh, jj|
    if h == hh
      j = jj
    end
  end
end

but it doesn't work. Also I think this is ugly code, so how would could it be written better/right?

I though I should compare the two hashes, and, if the second key is the same as the first, change the first hash value to the second hash's value.

Upvotes: 0

Views: 90

Answers (1)

maerics
maerics

Reputation: 156652

Just iterate over the entries in h2 and update the corresponding entry in h1 only if it already exists:

h2.each { |k,v| h1[k]=v if h1.include?(k) }
h1 # => {"a"=>1, "b"=>51, "c"=>2, "k"=>14 }

Also, if you want to update the entries as above and also add new entries from h2 you can simply use the Hash#merge! method:

h1.merge!(h2)
h1 # => {"a"=>1, "b"=>51, "c"=>2, "k"=>14, "d"=>8}

Upvotes: 1

Related Questions