0

I am building a CSV object and I have a dynamic set of header items. I build this 'header' row as follows:

headers = ["name", "email"]
questions.each do |q|
  headers << q
end
csv << headers

Although this works just fine, what I would like to do is have the call in one line without having to add the headers variable first.

So something like:

csv << ["name", "email", questions.each { |q| q }]

Obviously the above doesn't work because the each returns the 'questions' array.

Any suggestions?

Stefan
  • 109,145
  • 14
  • 143
  • 218
Christian-G
  • 2,371
  • 4
  • 27
  • 47

5 Answers5

2
csv << headers + questions
zolter
  • 7,070
  • 3
  • 37
  • 51
1

Use the splat operator as follow.

csv << ["name", "email", *questions]
oldergod
  • 15,033
  • 7
  • 62
  • 88
1

Just use Array#+:

csv << ["name", "email"] + questions

Or a bit shorter:

csv << %w(name email) + questions
Stefan
  • 109,145
  • 14
  • 143
  • 218
1

There's several methods to do this. I would use something like this:

headers = (['name', 'email'] << questions).flatten

See this question for more elaborate answers, also in regard to performance: How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

Community
  • 1
  • 1
KappaNossi
  • 2,656
  • 1
  • 15
  • 17
0
["name", "email", *questions.map { |q| q }]

map returns result array

Oleg Haidul
  • 3,682
  • 1
  • 22
  • 14