What is the Read function in Ruby?
The read method in Ruby allows you to read data stored in a file.
Syntax
Following is how you use the read method:
In the syntax below,
my_filerepresents the file pointer of the opened file:
Prerequisite for usage
To use this method, you must first open up a file using another ruby method called open and then call the read method on the file pointer of the opened file.
Parameters
The read requires no parameters to work, only an accompanying file pointer to call on.
Return value
The read method returns all the data stored in the file.
Examples
The following is an example where we read and print the stored data in a .txt file in the same directory as our main file:
# opening the filef = File.open("to_read.txt")# reading datadata_read = f.read# closing the filef.close# printing the read dataputs data_read
In Ruby,
putsis the function we use to print data out to the console similar toconsole.login Nodejs
Instead of opening and closing a file every time to read, you can use the File.read method. The File.read method takes in the name of the file you want to open and reads and returns the data stored in it.
Following is a code example showing its usage:
# opening the filedata_read = File.read("to_read.txt")# printing the read data to the consoleputs data_read
Free Resources