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?

0

5 Answers 5

2
csv << headers + questions
Sign up to request clarification or add additional context in comments.

Comments

1

Use the splat operator as follow.

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

Comments

1

Just use Array#+:

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

Or a bit shorter:

csv << %w(name email) + questions

Comments

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?

Comments

0
["name", "email", *questions.map { |q| q }]

map returns result array

2 Comments

objects.map { |q| q } isn't the same as objects ?
Only in this case, but if u want to do smth with each element and return a result object u need to use map

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.