Ruby 计算值在散列中重复的次数
我正在从mashable.com提取一个散列,我需要计算作者姓名的实例(author是键,值是作者姓名) 我想迭代散列并提取作者的姓名,然后计算它在mashable api的整个列表中重复的次数 这就是我所拥有的;它将散列转换为一个数组,对其进行迭代,将计数作为键添加到每个作者姓名中,然后将重复次数作为值添加 这将非常好,但我无法从mashable将其恢复到我的原始哈希中,以添加我想要显示的所有其他哈希项Ruby 计算值在散列中重复的次数,ruby,counting,hash,Ruby,Counting,Hash,我正在从mashable.com提取一个散列,我需要计算作者姓名的实例(author是键,值是作者姓名) 我想迭代散列并提取作者的姓名,然后计算它在mashable api的整个列表中重复的次数 这就是我所拥有的;它将散列转换为一个数组,对其进行迭代,将计数作为键添加到每个作者姓名中,然后将重复次数作为值添加 这将非常好,但我无法从mashable将其恢复到我的原始哈希中,以添加我想要显示的所有其他哈希项 all_authors = [] all_stories.each do |story|
all_authors = []
all_stories.each do |story|
authors = story['author']
all_authors << authors
end
counts = Hash.new(0)
all_authors.each do |name|
counts[name] += 1
end
counts.each do |key, val|
puts "#{key}: " "#{val}"
end
所有作者=[]
所有的故事,每个都是故事|
作者=故事['author']
所有作者这里有一个简化版本:
h = { a: 1, b: 2, c: 1, d: 1 }
h.count { |_, v| v == 1 } #=> 3
h.values.count(1) #=> 3
或者,您也可以按键分组,然后计数:
h.group_by(&:last).map { |v, a| [v, a.count] }.to_h #=> {1=>3, 2=>1}
这将根据散列的值对散列进行分组,计算键/值对数组中元素的次数。这里有一个更明确的版本:
grouped = h.group_by(&:last) #=> {1=>[[:a, 1], [:c, 1], [:d, 1]], 2=>[[:b, 2]]}
grouped.map { |v, a| [v, a.count] #=> [[1, 3], [2, 1]]
然后,最后一个to_h
将两个元素数组的数组转换为散列。@Michael Kohl这是一个很好的答案,我想我问错了问题。我最后做了以下几点:
author = story['author']
puts "Number of stories by #{story['author']}: #{author_count['author']}"
在我的“所有故事”循环中
是的,我很确定我试图将值“重新注入”到原始散列中,这是非常错误的
非常感谢您的帮助,但是我是否需要为每个要比较的键输入我要比较的值?@DavidJohnson这回答了您的问题吗?
grouped = h.group_by(&:last) #=> {1=>[[:a, 1], [:c, 1], [:d, 1]], 2=>[[:b, 2]]}
grouped.map { |v, a| [v, a.count] #=> [[1, 3], [2, 1]]
author = story['author']
puts "Number of stories by #{story['author']}: #{author_count['author']}"