write to a file in ruby

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.rb
File.open("example.txt", "w") do |file|
  file.write("Hello, world!")
end
74 chars
4 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.rb
File.open("example.txt", "w") do |file|
  file.puts("Line 1")
  file.puts("Line 2")
  file.puts("Line 3")
end
110 chars
6 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.rb
file = File.open("example.txt", "w")
file.write("Hello, world!")
file.close
76 chars
4 lines
main.rb
File.open("example.txt", "w") do |file|
  file.write("Hello, world!")
end
74 chars
4 lines

gistlibby LogSnag