我有一组名为@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)?
答案 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