Reputation: 454
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.
Upvotes: 7
Views: 2035
Reputation: 29
Another easy way
student_marks.keys.group_by{ |v| student_marks[v] }
{50=>["Alex", "Matt"], 54=>["Beth"]}
Upvotes: 1
Reputation: 110685
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.
Upvotes: 6
Reputation: 83680
Another way could be
student_marks.each.with_object(Hash.new([])){ |(k,v), h| h[v] += [k] }
#=> {50=>["Alex", "Matt"], 54=>["Beth"]}
Upvotes: 4
Reputation: 106882
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"]}
Upvotes: 6