Donato
Donato

Reputation: 2777

How to merge two hashes and remove extra elements

I have this hash:

a={a: 'a', b: 'b'}

and this hash:

b={c: 'c', d: 'd', e: 'e'}

And I want to merge them, but since hash a only contains two keys, I want to make sure I only keep the two initial keys of hash b, so instead of this:

a.merge b
=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d", :e=>"e"} 

I would like a result that looks like this:

=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d" } 

so I kept the first two hash keys of b, since a only had two hash keys. If a had three hash keys, then we would have kept all three of b's, and so forth.

The documentation shows a delete method, but it forces me to specify a key. I won't know what the key is, I just want to remove extra elements.

How can I approach this?

Upvotes: 1

Views: 115

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

Here's another way, assuming none of b's keys are in a:

a = { a: 'a', b: 'b' }
b = { c: 'c', d: 'd', e: 'e' }

keepers = b.keys[0,a.size]
  #=> [:c, :d]
a.merge(b.select { |k,_| keepers.include?(k) })
  #=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d"}

Note that it has only been since Ruby version 1.9 that hashes have maintained the insertion order of keys.

Upvotes: 0

xdazz
xdazz

Reputation: 160843

You could do like this:

Hash[a.to_a + b.to_a[0...a.length]]
# or 
Hash[a.to_a + b.to_a.take(a.length)]

Turn to array then slice b by a's length, turn to hash at last.

Upvotes: 1

Related Questions