ruby 减少哈希值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13882956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:36:07  来源:igfitidea点击:

Reduce Hash Values

rubyhashreduce

提问by richsoni

I am having trouble with the syntax for reduce. I have a hash of the following format:

我在使用 reduce 的语法时遇到了问题。我有以下格式的哈希:

H = {"Key1" => 1, "Key2" => 2}

I would like to use reduce to find the sum of the values in this function.

我想使用 reduce 来查找此函数中的值的总和。

Something Like

就像是

H.reduce(0) {|memo, elem| memo+=elem}

I know this is wrong. I dont understand how I can make elem the value of the hash.

我知道这是错误的。我不明白如何让 elem 成为哈希值。

回答by steenslag

You can make elemcontain the value by splitting it up in 2 variables:

您可以elem通过将其拆分为 2 个变量来包含该值:

H.reduce(0) {|memo, (key, val)| memo += val}

回答by maerics

Use Enumerable#reduce, if you're ok with getting nilif the hash happens to be empty:

如果哈希恰好为空Enumerable#reduce,请使用,如果您可以接受nil

H.values.reduce(:+) # => 3
Hash.new.values.reduce(:+) # => nil

To safely get 0when the hash is empty, use:

0在哈希为空时安全地获取,请使用:

H.values.reduce(0) { |sum,x| sum + x } # or...
H.reduce(0) { |sum,(key,val)| sum + val } # ...if you need to inspect the key

Here's a quick benchmark, for kicks. Note that it appears to be slightly faster to reduce just the values rather than values from the key/value pairs:

这是一个快速基准,用于踢球。请注意,仅减少值而不是键/值对中的值似乎会稍微快一点:

                               user     system      total        real
H.values.reduce(:+)        4.510000   0.080000   4.590000 (  4.595229)
H.values.reduce(0) {...}   4.660000   0.080000   4.740000 (  4.739708)
H.reduce(0) {...}          5.160000   0.070000   5.230000 (  5.241916)
require 'benchmark'

size = 1_000
hash = Hash[* Array.new(size*2) { rand } ]

N=10_000
Benchmark.bm(24) do |x|
  x.report('H.values.reduce(:+)')      { N.times { hash.dup.values.reduce(:+) } }
  x.report('H.values.reduce(0) {...}') { N.times { hash.dup.values.reduce(0) { |sum,x| sum + x } } }
  x.report('H.reduce(0) {...}')        { N.times { hash.dup.reduce(0) { |sum,(_,v)| sum + v } } }
end

回答by yasu

Try this:

尝试这个:

H.reduce(0) { |memo, elem| memo += elem[1] }

or

或者

H.reduce(0) { |memo, (key, value)| memo += value }

回答by astorije

I know I'm excavating this one, but if you happen to use Rails, the .summethodcan help:

我知道我正在挖掘这个,但是如果您碰巧使用 Rails,该.sum方法可以提供帮助:

H = {"Key1" => 1, "Key2" => 2}
=> {"Key1"=>1, "Key2"=>2}
> H.values.sum
=> 3

Advantage is that it returns 0on empty hashes:

优点是它返回0空哈希值:

> {}.values.sum
=> 0
> {}.values.reduce(:+)
=> nil

I noticed it was Rails-specific only after typing this answer. I know the OP didn't add the Rails tag, but I figured it might be useful for people stopping by.

仅在输入此答案后,我才注意到它是特定于 Rails 的。我知道 OP 没有添加 Rails 标签,但我认为它可能对路过的人有用。

Note that as of Ruby 2.4.0, .sumis now available.

请注意,从 Ruby 2.4.0 开始,.sum现在可用

回答by astorije

h = {"Key1" => 1, "Key2" => 2}

h.values.inject(0){|f,v| f += v.to_i }
# => 3

or

或者

h.values.inject(:+)
# => 3