PEF
PEF

Reputation: 973

How do I count different values of an attribute from an array of hashes in Ruby?

I have an array of hashes called @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" }]

What is the method to count the different values of user_name in @messages (which should give 3 here)?

Upvotes: 2

Views: 535

Answers (3)

Andrew Grimm
Andrew Grimm

Reputation: 81510

Another way would be using 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

Upvotes: 0

Michael Kohl
Michael Kohl

Reputation: 66837

YOu already have your answer, but if you are also interested in the actual number per user_name, you could do

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

Then counts.size tells you how many distinct names there are.

Upvotes: 0

Maurício Linhares
Maurício Linhares

Reputation: 40333

There is no method to do it, the simplest solution I can think of is using 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

Upvotes: 3

Related Questions