2011-09-16 23 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" }] 

(ここでは3を与える必要があります)@messagesでuser_nameの異なる値をカウントする方法は何ですか?

答えて

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

関連する問題