我有这个哈希
{
19132=>{
:occurences=>34,
:name=>"bar"
},
19133=>{
:occurences=>19,
:name=>"foo"
}
}
我想在每个键(19132和19133)的新键(为什么不是total
)中添加出现次数(34 + 19)。
我有类似的事情:
my_hash = {19132=>{:occurences=>34, :name=>"bar"}, 19133=>{:occurences=>19, :name=>"foo"}}
my_hash.values.inject{|memo, el| memo.merge(el){|k, old_v, new_v| old_v + new_v if k.is_a?(Numeric)}}
我找到了一些帮助Here,但我仍然坚持合并。我甚至不知道这种方法是否可以解决我的问题。
答案 0 :(得分:1)
首先,遍历所有内部哈希并计算总数:
total = h.values.inject(0) { |total, hash| total + hash[:ocurrences] }
然后,将总数添加到内部哈希值:
h.keys.each{|k| h[k][:total] = total}
答案 1 :(得分:0)
我尝试分两步完成:找到总数并合并总数。
hash = {19132=>{:occurences=>34, :name=>"bar"}, 19133=>{:occurences=>19, :name=>"foo"}}
total = hash.collect(&:first).sum
# => 38265
hash.each{|h| h[1].merge!({"total" => total})}
# => {19132=>{:occurences=>34, :name=>"bar", "total"=>38265}, 19133=>{:occurences=>19, :name=>"foo", "total"=>38265}}
答案 2 :(得分:0)
sum = h.values.inject(0) {|sum, h| sum + h[:occurences] }
# => 53
h.map {|k, v| v[:total] = sum; [k,v]}.to_h
# => { 19132=>{:occurences=>34, :name=>"bar", :total=>53},
# 19133=>{:occurences=>19, :name=>"foo", :total=>53} }
答案 3 :(得分:0)
你可以这样做:
tot = h.each_value.reduce(0) { |t, g| t + g[:occurrences] }
h.merge(h) { |*_,g| g.merge("total"=>tot) }
# => {19132=>{:occurrences=>34, :name=>"bar", "total"=>53},
# 19133=>{:occurrences=>19, :name=>"foo", "total"=>53}}
这不会改变原始哈希:
h #=> {19132=>{:occurrences=>34, :name=>"bar"},
# 19133=>{:occurrences=>19, :name=>"foo"}}
如果您希望更改h
:
h.merge!(h) { |*_,g| g.merge!("total"=>tot) }
有效,但是:
h.each_value { |g| g["total"] = tot }
更好。