2011-09-16 77 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