Donato Donato - 7 months ago 8
Ruby Question

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?

Answer

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.

Comments