Ruby - Read an I/O stream line by line using gets

Description

Read an I/O stream line by line using gets

Demo

File.open("main.rb") do |f| 
  2.times { puts f.gets } 
end

Result

gets isn't an iterator like each or each_byte.

You have to call it multiple times to get multiple lines.

Here, it was used twice, and pulled out the first two lines of the example file.

gets can accept an optional delimiter:

Demo

File.open("main.rb") do |f| 
  2.times { puts f.gets(',') } 
end

Result

The following code uses a noniterative version of each_byte called getc:

Demo

File.open("main.rb") do |f| 
  2.times { puts f.getc } 
end

Result

getc returns the actual character in a string rather than the numerical byte value.

Related Topic