
Kevin R. answered 03/18/22
Software Engineer at tech company that uses Ruby/Rails as main tool.
Writing to a text file is very easy in Ruby due to the Ruby File class/object. There are a few ways to go about this:
To open and write to a new file you can do something like this:
To open and write to an existing text file (append), you can do this:
It is also important to note that if you want to take an array or an object of some kind, it has to be converted to a string first before it can be written to a file. There are more Ruby file methods that allow you to do things like check if a file exists, loop through directories on your system, read different files, and more.