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.
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"]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With