Jimmy Wang Jimmy Wang - 1 year ago 102
Ruby Question

What is f.gets.chomp doing? (Learn Ruby Hard Way: Exercise 20)

Link to the exercise: http://learnrubythehardway.org/book/ex20.html

I'm having trouble understanding the output of the exercise where it displays:

1, This is line 1
2, This is line 2
3, This is line 3

I don't understand which part of the code is causing the program to read the specific # of line. How does it know to read line 1 vs line 2 vs line 3?

Does it have something to do with this part:

def print_a_line(line_count, f)
puts "#{line_count}, #{f.gets.chomp}"

I thought gets.chomp is for getting the user input from commandline (and cut off the line break).

Answer Source

IO#gets return a line (as a string) from a file with newline intact. (f.gets in the code). Every time you call it, it return next line from the file.

String#chomp return a new string without the trailing newline:

"This is line 1\n".chomp
# => "This is line 1"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download