To write to a file in Ruby, you can use the File class and its .open method to create a new file object or open an existing one. You should specify the name of the file you want to write to, the mode in which you want to open it, and optionally a block that will execute the code to write to the file.
Here is an example of creating a new file and writing a string to it:
main.rb74 chars4 lines
This code opens a new text file titled "example.txt" in write mode ("w"), and passes the file object to a block. The write method is called on the file object and passed a string argument "Hello, world!", which is written into the file.
If you want to write multiple lines to the file, you can use the puts method instead of write. Here is an example:
main.rb110 chars6 lines
This code writes three lines to the file "example.txt", each on a separate line. The puts method writes a line of text and then inserts a newline character at the end.
Remember to close the file when you finish writing to it by calling the .close method on the file object, or using a block as shown in the examples (which will automatically close the file).
main.rb76 chars4 lines
main.rb74 chars4 lines
gistlibby LogSnag