read a file in ruby

To read a file in Ruby, you need to open the file and then read its contents. Here is an example code snippet that demonstrates this:

main.rb
# Open file in read mode
file = File.open("file.txt", "r")

# Read contents of file
contents = file.read()

# Close the file
file.close()

# Print the contents of file to the console
puts contents
197 chars
12 lines

In this code, we first open the file in read mode using the File.open method. The first argument is the path of the file, and the second argument specifies the mode in which to open the file ("r" for read, "w" for write, "a" for append, etc.).

Next, we read the contents of the file using the read method of the file object. This method reads the entire contents of the file as a string.

Finally, we close the file using the close method, which frees up any system resources used by the file.

And lastly, we print the contents of the file to the console using the puts method.

gistlibby LogSnag