我有兩個哈希看起來像這樣:連接兩個紅寶石哈希通過按鍵
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