D
D
Denis Black2017-03-15 16:31:56
ruby
Denis Black, 2017-03-15 16:31:56

Ruby - Reading 2D array into CSV?

Hello everyone, there is a two-dimensional array in the form:

#⇒ [
#  [0] [
#    [0] "11",
#    [1] "Название1",
#    [2] "Название2",
#    [3] "Название3",
#    [4] "Название4",
#    [5] "Название5"
#  ],
#  [1] [
#    [0] "22",
#    [1] "Название1",
#    [2] "Название2",
#    [3] "Название3",
#    [4] "Название4",
#    [5] "Название5"
#  ]
# ]

How to read this 2D array into a csv file?
I do this, but it displays in one column, but it should be like this:

Name1,Name2,Name3,Name4,Name5 Name1, Name2, Name3, Name4,
Name5

out_file = File.open('csv_file.csv', 'w')
out_file.puts "Name1,Name2,Name3,Name4,Name5"
input.each_index do |inx|
  p "{#{inx}} =>"
  inx.each do |val|
    out_file.puts val.chomp
  end
end

Plus, it puts \r at the end - as I understand it, add chomp
It also fails to add Do I join(',')
need to overwrite the line? to_a?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Cherny, 2017-03-16
@qskyhigh

Decision:

File.write('csv_file.csv', input.map { |e| e.join(",") }.join($/))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question