我正在构建一个CSV对象,我有一组动态的标题项。我按如下方式构建了这个“标题”行:
headers = ["name", "email"]
questions.each do |q|
headers << q
end
csv << headers
虽然这样做很好,但我想要做的是在一行中调用,而不必先添加headers
变量。
类似于:
csv << ["name", "email", questions.each { |q| q }]
显然上述情况不起作用,因为each
返回'questions'数组。
有什么建议吗?
答案 0 :(得分:2)
csv << headers + questions
答案 1 :(得分:1)
使用splat运算符如下。
csv << ["name", "email", *questions]
答案 2 :(得分:1)
答案 3 :(得分:1)
有几种方法可以做到这一点。我会用这样的东西:
headers = (['name', 'email'] << questions).flatten
请参阅此问题,以获得更详细的答案,以及有关效果的问题:How do you add an array to another array in Ruby and not end up with a multi-dimensional result?
答案 4 :(得分:0)
["name", "email", *questions.map { |q| q }]
map
返回结果数组