Donato Donato - 1 year ago 52
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
only contains two keys, I want to make sure I only keep the two initial keys of hash
, 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
, since
only had two hash keys. If
had three hash keys, then we would have kept all three of
's, and so forth.

The documentation shows a
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download