2013-07-20 60 views
1

如何實現「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} 
+0

* + 1 *有趣的問題...... –

回答

4

沒有必要的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} 
+0

驚人的速度,Priti! –

+0

@ SergRa6n是的..我今天在紅寶石模式.. :))) –

+0

@mu太短,感謝您的編輯.. :)) –

0
class Hash 
    def custom_merge other 
    merge(other){|_, *a| a} 
    end 
end 
+1

請爲您的答案添加解釋:**爲什麼**能解決問題? – fuxia