Add each array element to the lines of a file in ruby

edc505 picture edc505 · Sep 19, 2013 · Viewed 47.9k times · Source

If I have an array of strings e.g.

a = ['a', 'b', 'c', 'd']

and I want to output the elements, to a file (e.g. .txt) one per line. So far I have:

File.new("test.txt", "w+")
File.open("test.txt", "w+") do |i|
    i.write(a)
end

This gives me the array on one line of the test.txt file. How can I iterate over the array, adding each value to a new line of the file?

Answer

Stefan picture Stefan · Sep 19, 2013

Either use Array#each to iterate over your array and call IO#puts to write each element to the file (puts adds a record separator, typically a newline character):

File.open("test.txt", "w+") do |f|
  a.each { |element| f.puts(element) }
end

Or pass the whole array to puts:

File.open("test.txt", "w+") do |f|
  f.puts(a)
end

From the documentation:

If called with an array argument, writes each element on a new line.