如何从Ruby中的哈希数组中计算属性的不同值?

时间:2011-09-16 12:27:43

标签: ruby arrays hash

我有一组名为@messages的哈希:

[{ "id" => "1", "user_name" => "John", "content" => "xxxxx" },
 { "id" => "2", "user_name" => "John", "content" => "yyyyy" },
 { "id" => "3", "user_name" => "Paul", "content" => "zzzzzz" },
 { "id" => "4", "user_name" => "George", "content" => "xxyyzz" }]

在@messages中计算user_name的不同值的方法是什么(这里应该给出3)?

3 个答案:

答案 0 :(得分:3)

没有方法可以做到,我能想到的最简单的解决方案是使用map:

attributes = [{ "id" => "1", "user_name" => "John", "content" => "xxxxx" },
   { "id" => "2", "user_name" => "John", "content" => "yyyyy" },
   { "id" => "3", "user_name" => "Paul", "content" => "zzzzzz" },
   { "id" => "4", "user_name" => "George", "content" => "xxyyzz" }]

count = attributes.map { |hash| hash['user_name'] }.uniq.size

答案 1 :(得分:0)

你已经有了答案,但是如果你对每user_name的实际数字感兴趣,你可以做到

counts = attributes.inject(Hash.new{|h,k|h[k]=0}) { |counts, h| counts[h['user_name']] += 1 ; counts}

然后counts.size会告诉您有多少不同的名称。

答案 2 :(得分:0)

另一种方法是使用group_by

attributes = [{ "id" => "1", "user_name" => "John", "content" => "xxxxx" },
   { "id" => "2", "user_name" => "John", "content" => "yyyyy" },
   { "id" => "3", "user_name" => "Paul", "content" => "zzzzzz" },
   { "id" => "4", "user_name" => "George", "content" => "xxyyzz" }]
attributes.group_by{|hash| hash["user_name"]}.count # => 3