Read an I/O stream line by line using gets
File.open("main.rb") do |f|
2.times { puts f.gets }
end
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:
File.open("main.rb") do |f| 2.times { puts f.gets(',') } end
The following code uses a noniterative version of each_byte called getc:
File.open("main.rb") do |f|
2.times { puts f.getc }
end
getc returns the actual character in a string rather than the numerical byte value.