Tuesday, March 19, 2013

Ruby array to text file.

I've been learning ruby for a few months now, and I'm still a serious beginner, but I'm getting somewhere. However there are some questions that good googling still seems to take a good while to answer, so I thought I would post them here, both for my reference and for public use.

Problem: I have an array, and I want to save it as a text file with each array entry on a new line.

Question: How do I save an array to a text file with ruby.

Answer:

array = [ 'dog', 'cat', 'fish', 'bear']
out_file = File.open("output.txt", "w")
array.each do |line|
out_file.puts line
end

So there it is. If I've done something wrong, forgive me please. As I said I'm just getting started and I welcome any feedback.

No comments: