如何實現「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}
如何實現「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}
沒有必要的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}
驚人的速度,Priti! –
@ SergRa6n是的..我今天在紅寶石模式.. :))) –
@mu太短,感謝您的編輯.. :)) –
class Hash
def custom_merge other
merge(other){|_, *a| a}
end
end
請爲您的答案添加解釋:**爲什麼**能解決問題? – fuxia
* + 1 *有趣的問題...... –