Ruby hash group by value

Viewed 1281

I have a ruby hash containing student name and mark as follows.

student_marks = {
    "Alex" => 50,
    "Beth" => 54,
    "Matt" => 50
}

I am looking for a solution to group students according to their mark.

{
    50 => ["Alex", "Matt"],
    54 => ["Beth"]
}

I have tried group_by but it didn't give me the desired result. Following is the result of using group_by.

student_marks.group_by {|k,v| v}
{50=>[["Alex", 50], ["Matt", 50]], 54=>[["Beth", 54]]}

Thanks in advance.

4 Answers
student_marks.group_by(&:last).transform_values { |v| v.map(&:first) }
  #=> {50=>["Alex", "Matt"], 54=>["Beth"]}

Hash#transform_values made its debut in Ruby MRI v2.4.0.

I would do something like this:

student_marks.group_by { |k, v| v }.map { |k, v| [k, v.map(&:first)] }.to_h
#=> { 50 => ["Alex", "Matt"], 54 => ["Beth"]}

Another way could be

student_marks.each.with_object(Hash.new([])){ |(k,v), h| h[v] += [k] }
#=> {50=>["Alex", "Matt"], 54=>["Beth"]}

Another easy way

student_marks.keys.group_by{ |v| student_marks[v] }
{50=>["Alex", "Matt"], 54=>["Beth"]}
Related