我有两个哈希看起来像这样:连接两个红宝石哈希通过按键
h1 = {key1: 'Roses are', key2: 'Violets are'}
h2 = {key1: 'Red', key2: 'Blue'}
我想通过键加入他们的行列,让我得到这样一个哈希:
result = {'Roses are' => 'Red', 'Violets are' => 'Blue'}
我有一些代码,做的伎俩:
result = {}
h1.each { |key, value| result[value] = h2[key] }
我不知道是否有在标准库的方法来做到这一点,还是这个可以用更少的做代码。
更少的代码?这只有2行。如果你真的需要,你可以使用each_with_object将它减少到一行,如:'result = h1.each_with_object({}){|(key,value),h3 | h3 [value] = h2 [key]}' – Santhosh