The IO
instance is the basis for all input and output operations in Ruby. Using this instance, we can read a file and get its contents line by line using the foreach()
method. This method takes the name of the file, and then a block which gives us access to each line of the contents of the file.
IO.foreach(filename) {|x| # do something with each line x}
filename
: This represents the file we want to get its contents line by line.
x
: This represents each line of the file that was provided by the block of the foreach()
method.
The value returned is the contents of the file line by line.
# create a file text.txt and read its contents line by lineIO.foreach("text.txt") {|x| puts x }
text.txt
and we manually write in some few texts, line by line. Then, we use the foreach()
method of the IO
instance, and inside our application file, we print each line of the file test.txt
to the console.# create a file text.txt and read its contents line by lineIO.foreach("text.txt") {|x| puts "#{x.upcase}" }
text.txt
and we manually write in some texts, line by line. Then we use the foreach()
method of the IO
instance, and inside our application file, we print each line of the file test.txt
to the console. Each line is a string of texts which we convert to uppercase and print to the console.