我现在发现很难在数组中分组散列,我已经尝试过group_by方法,但没有任何进展。
students = [ {name: "James", cohort: :December}, {name: "David", cohort: :April}, {name: "Kyle", cohort: :December} ]
什么是最简单的方法来分组学生的队列......例如,它会打印出这样的
December = James, Kyle April = David
谢谢!
q43xntqr1#
使用group_by方法,如下所示
students = [ {name: "James", cohort: :December}, {name: "David", cohort: :April}, {name: "Kyle", cohort: :December} ] grouped_students = students.group_by { |student| student[:cohort] } grouped_students.each do |cohort, students| puts "#{cohort} = #{students.map { |student| student[:name] }.join(', ')}" end
下面是另一种使用each_with_object方法的方法。
each_with_object
students_by_cohort = students.each_with_object({}) do |student, result| cohort = student[:cohort] result[cohort] ||= [] result[cohort] << student[:name] end students_by_cohort.each do |cohort, students| puts "#{cohort}: #{students.join(", ")}" end
输出
1条答案
按热度按时间q43xntqr1#
使用group_by方法,如下所示
下面是另一种使用
each_with_object
方法的方法。输出