【发布时间】:2017-10-11 20:20:16
【问题描述】:
我有两个看起来像这样的哈希:
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] }