使用数组中的键迭代散列,并对结果求和
Iterate over a hash using keys from an array, and sum the results
我有一个 Hash
将一堆 ID 索引到一个值,例如:
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
arr.map {|i| hash[i]}.reduce(:+)
你可能再也找不到比这更多的 ruby-ish :)
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
我有一个 Hash
将一堆 ID 索引到一个值,例如:
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
arr.map {|i| hash[i]}.reduce(:+)
你可能再也找不到比这更多的 ruby-ish :)
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