2

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)?

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

yep, i had seen this way of solving. But hadn't gone further with size. Works as well!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.