0

I am using csv to export data. I am dynamically populating the fields and in order to do so i have added loop in to csv:

csv_data = CSV.generate do |csv|
  csv << [
  @userHeaders.each do |user|
    "#{user.name}"
  end
  ]
end

but this returns some thing like this: [#<User >, #<User >, #<User >, #<User >]

but when i tried to inspect the value after assigning it to a variable, it displays all the names that have been passed.

name = "#{user.name}"
puts name.inspect  # (this diaplays all the names)

is there any format to display the data while looping inside csv?

please guide with answer thanks

1 Answer 1

1

Try just using the map (aka collect) method of your array:

csv_data = CSV.generate do |csv|
  csv << @userHeaders.map { |user| user.name }
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it works great. i have one more case where data is not displaying properly, while displaying data in EXcel, it show like this ["jack","Tom","Kevin"] in a colunm. this is not returning as separate column. this is code i used just adding two more fields before loop csv << [ "Country","State", @userHeaders.map { |user| user.name }, ]
You probably want to use csv << ["Country", "State"] + @userHeaders.map { |user| user.name } instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.