Add each array element to the lines of a file in ruby
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.
As an alternate, you could simply join the array with "\n" so that each element is on a new line, like this:
a = %w(a b c d)File.open('test.txt', 'w') {|f| f.write a.join("\n")}
If you don't want to override the values already in the text file so that you're simply adding new information to the bottom, you can do this:
a = %w(a b c d)File.open('test.txt', 'a') {|f| f << "\n#{a.join("\n")}"}