2011-09-16 51 views
2

我已经散列的数组称为@messages:如何计算Ruby中哈希数组属性的不同值?

[{ "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" }] 

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

回答

3

没有方法做到这一点,我能想到的最简单的办法是使用地图:

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 
+0

伟大工程的感谢! – PEF

0

您已经有了答案,但如果你也有兴趣在实际的每user_name,你可以做

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

然后counts.size告诉你有多少个不同的名字。

+0

是的,我已经看到了解决这个问题的方法。但没有进一步与'大小'。也适用! – PEF

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 
+0

工作以及谢谢! – PEF