You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中如何对数组内的哈希按cohort分组?求最简实现方式

按Cohort分组学生数组的最简实现

你提到的group_by其实就是最适合的方法,可能是没完成后续的名字提取和格式化步骤。直接用以下代码就能实现需求:

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

# 按cohort分组,然后遍历输出格式内容
students.group_by { |student| student[:cohort] }.each do |cohort, student_group|
  # 提取当前组所有学生的名字,用逗号连接
  student_names = student_group.map { |s| s[:name] }.join(', ')
  puts "#{cohort} = #{student_names}"
end

运行这段代码后,会输出:

December = James, Kyle
April = David

步骤说明:

  • group_by { |student| student[:cohort] }:将学生数组按照:cohort字段分组,得到一个以cohort为键、对应学生哈希数组为值的新哈希。
  • map { |s| s[:name] }:从每个分组的学生哈希中提取名字,生成名字数组。
  • join(', '):把名字数组转换为逗号分隔的字符串,符合输出格式要求。

内容的提问来源于stack exchange,提问作者wanderingnowhere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:09:59