Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby hash group by value

Tags:

ruby

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.

like image 811
Sambit Avatar asked Sep 13 '18 16:09

Sambit


3 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.

like image 103
Cary Swoveland Avatar answered Nov 10 '22 18:11

Cary Swoveland


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"]}
like image 5
spickermann Avatar answered Nov 10 '22 17:11

spickermann


Another way could be

student_marks.each.with_object(Hash.new([])){ |(k,v), h| h[v] += [k] }
#=> {50=>["Alex", "Matt"], 54=>["Beth"]}
like image 4
fl00r Avatar answered Nov 10 '22 16:11

fl00r