Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个Hash将一堆 ID 索引到一个值,例如:
Hash
hash = {1: 3.00, 2: 4.00, 3: 2.00, 4: 15.00, 5: 12.00, 6: 1.00}
我有一个看起来像这样的数组:
arr = [2, 3, 6]
什么是一种简短的 Ruby 惯用方式来迭代我的数组并将哈希中相应键的累积总数相加?
上述结果将等于:
4.00 + 2.00 + 1.00 == 7.00
您可能无法获得比这更多的红宝石 :)
hash.values_at(*arr).reduce(:+)
hash = {1=>3.0, 2=>4.0, 3=>2.0, 4=>15.0, 5=>12.0, 6=>1.0} arr = [2, 3, 6] arr.reduce(0) { |t,e| t + hash[e] } #=> 7.0
arr.map {|i| hash[i]}.reduce(:+)