ruby 在数组中分组哈希

ruarlubt  于 2023-04-11  发布在  Ruby
关注(0)|答案(1)|浏览(100)

我现在发现很难在数组中分组散列,我已经尝试过group_by方法,但没有任何进展。

students = [
    {name: "James", cohort: :December},
    {name: "David", cohort: :April},
    {name: "Kyle", cohort: :December}  
]

什么是最简单的方法来分组学生的队列......例如,它会打印出这样的

December = James, Kyle
April = David

谢谢!

q43xntqr

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方法的方法。

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

输出

December = James, Kyle
April = David

相关问题