在数组中分组哈希

  • 本文关键字:哈希 数组 ruby
  • 更新时间 :
  • 英文 :


我目前发现很难在数组内分组哈希值。我尝试了group_by方法,但没有任何进展。

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

按队列分组学生最简单的方法是什么?例如:它将输出如下

December = James, Kyle
April = David

谢谢!

使用如下所示的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

最新更新