1

我有一个哈希数组,我想要唯一的值并从中计数。我有:

a = [{:key => 2}, {:key => 1}, {:key => 4}, {:key => 1}]

我想看:

a = [{:key => 2}, {:key => 1, :count =>2}, {:key => 4}]
4

4 回答 4

2

尝试这个:

a = [{:key => 2}, {:key => 1}, {:key => 4}, {:key => 1}]
b = a.clone
a.uniq!
a.inject([]) { |result,h| h[:count]=b.count(h) if b.count(h) > 1 ; result << h; result }

 => [{:key=>2}, {:key=>1, :count=>2}, {:key=>4}]
于 2012-07-17T13:38:07.283 回答
1

您只需要遍历数组并计算每个键出现的次数,然后通过使用结果构建一个新数组来将它们加在一起。

下面的代码片段应该做到这一点。

a = [{:key => 2}, {:key => 1}, {:key => 4}, {:key => 1}]

counts = Hash.new(0)

a.map do |item|
  counts[item[:key]] += 1
end

a = counts.collect do |key, count|
  if count > 1
    {:key => key, :count => count}
  else
    {:key => key}
  end
end
于 2012-07-17T13:20:04.683 回答
0

尝试这个:

a.each {|h| count = a.count(h); if count > 1; dup_h = h.clone; h.merge!({:count => count}); a.delete(dup_h); end }
于 2012-07-18T08:18:09.713 回答
-1

最简洁的方式(我认为)是这样的:

a.uniq.map{|hsh| c = a.count(hsh); c == 1 || hsh[:count] = c; hsh}

或者如果您不想修改 a 中的哈希值:

a.uniq.map{|hsh| h = hsh.dup; c = a.count(hsh); c == 1 || h[:count] = c; h}

产生不同结果的(略微)更漂亮的解决方案是:

a.uniq.group_by{|hsh| a.count(hsh)}
#=> {1=>[{:key=>2}, {:key=>4}], 2=>[{:key=>1}]}

查看有关Enumerable#countEnumerable#group_by的文档,以了解更多关于您可以使用它们做什么的信息。
Ruby 的核心其实是相当强大的。

于 2012-07-17T13:58:45.853 回答