52

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?

0

5 Answers 5

123

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.

3
  • Your first suggestion was what I wanted. Thanks.
    – edc505
    Sep 20, 2013 at 8:31
  • 1
    Just a heads-up for people using a set instead of an array: only the first version works.
    – daniel f.
    Mar 21, 2017 at 8:51
  • 1
    @danielf. that's correct, as mentioned in the documentation, you have to call puts with an array argument to get that behavior.
    – Stefan
    Mar 21, 2017 at 9:52
24

There is a quite simpler solution :

IO.write("file_name.txt", your_array.join("\n"))
2
  • @Dika Suparlan, welcome to SO. A little explanation is also helpful. Not only does it validate your answer but it gives the OP an indication of what they need to do both with the current issue and potentially in future situations. Im sure I'm not alone in wanting to learn from the SO community rather than just being given solutions. The greatest sense of success is in overcoming a good challenge. ;-) Sep 20, 2016 at 13:47
  • 1
    This should be the preferred answer. From the doc -- ruby-doc.org/core-2.4.2/IO.html -- IO.write(name, string [, offset] [, opt]) → integer --- Opens the file, optionally seeks to the given offset, writes string, then returns the length written. write ensures the file is closed before returning. If offset is not given, the file is truncated. Otherwise, it is not truncated. Dec 1, 2017 at 18:33
9

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")}"}
4

Use Array#each to iterate each element. When writing to the file, make sure you append newline(\n), or you will get a file with abcd as content:

a = ['a', 'b', 'c', 'd']
File.open('test.txt', 'w') do |f|
  a.each do |ch|
    f.write("#{ch}\n")
  end
end
4
  • @SergioTulentsev, See Enumerable documentation. There's no each.
    – falsetru
    Sep 19, 2013 at 16:45
  • What? All these years I thought that each belongs to Enumerable. Sep 19, 2013 at 16:46
  • @SergioTulentsev, Enumerable is a just mixin. It does not define each itself.
    – falsetru
    Sep 19, 2013 at 16:46
  • 1
    Right, it depends on each. Sep 19, 2013 at 16:47
3

Another simple solution:

directory = "#{Rails.root}/public/your_directory" #create your_directory before
file_name = "your_file.txt"
path = File.join(directory, file_name)
File.open(path, "wb") { |f| f.write(your_array.join("\n")) }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.