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

Ruby数组填充问题:如何将months元素追加到嵌套数组达成目标结构

Hey there! Let's break down what's happening with your code and get it to produce that goal array you want.

The Problem with Your Current Code

Your map block is returning the result of months.each { ... }, and since each always returns the original array it was called on (in this case, months), that's why you're getting an array of two copies of months instead of your modified topic sets. You're modifying the topic_set arrays correctly with <<, but you're not returning those modified arrays from the block—you're returning the output of each instead.

The Fix

You just need to make sure your map block returns the updated topic_set after you've added the months to it. There are a couple clean ways to do this:

Option 1: Explicitly return the modified topic set

months = ["2019-01-01", "2019-02-01", "2019-03-01", "2019-04-01"]
monthly_doc_count_for_topic = [ ["foo","2019-02-01: 186904","2019-03-01: 196961"], ["bar","2019-01-01: 8876","2019-04-01: 8694"] ]

goal = monthly_doc_count_for_topic.map do |topic_set|
  months.each { |month| topic_set << month }
  topic_set # This is what map will use as the new element
end

Option 2: Use concat for a cleaner one-liner

concat merges another array directly into the current one and returns the updated array, which is perfect for this use case:

goal = monthly_doc_count_for_topic.map do |topic_set|
  topic_set.concat(months)
end

What You'll Get

Either of these will produce exactly the goal array you're after:

[
  ["foo","2019-02-01: 186904","2019-03-01: 196961","2019-01-01","2019-02-01","2019-03-01","2019-04-01"],
  ["bar","2019-01-01: 8876","2019-04-01: 8694","2019-01-01","2019-02-01","2019-03-01","2019-04-01"]
]

Bonus: Keep the Original Array Intact

If you don't want to modify the original monthly_doc_count_for_topic arrays, just make a duplicate of each subarray before adding the months:

goal = monthly_doc_count_for_topic.map do |topic_set|
  topic_set.dup.concat(months)
end

This way your original data stays untouched, and goal is a brand new set of arrays.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 09:47:33