[英]Ruby hash group by value
I have a ruby hash containing student name and mark as follows.我有一个包含学生姓名和标记的 ruby 哈希值,如下所示。
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.我试过group_by
但它没有给我想要的结果。 Following is the result of using group_by
.以下是使用group_by
的结果。
student_marks.group_by {|k,v| v}
{50=>[["Alex", 50], ["Matt", 50]], 54=>[["Beth", 54]]}
Thanks in advance.提前致谢。
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"]}
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. Hash#transform_values在 Ruby MRI v2.4.0 中首次亮相。
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"]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.