如何为哈希创建自定义“合并”方法?

时间:2013-07-20 20:09:57

标签: ruby arrays sorting hashmap

如何实施“custom_merge”方法?

h1 = {a: 1, c: 2} 
h2 = {a: 3, b: 5} 

这是一个标准的“合并”方法实现:

h1.merge(h2) # => {:a=>3, :c=>2, :b=>5}

我想要的“custom_merge”方法应该实现:

h1.custom_merge(h2) # {a: [1, 3], b: 5, c: 2}

2 个答案:

答案 0 :(得分:5)

不需要custom_merge方法。带有块的Ruby核心Hash#merge将帮助你。

h1 = {a: 1, c: 2} 
h2 = {a: 3, b: 5} 
h3 = h1.merge(h2){|k,o,n| [o,n]}
h3
# => {:a=>[1, 3], :c=>2, :b=>5}

答案 1 :(得分:0)

class Hash
  def custom_merge other
    merge(other){|_, *a| a}
  end
end
相关问题