简体   繁体   中英

Passing an gets.chomp as an argument

input_file = ARGV.first

def print_all(f)
    puts f.read
end

def rewind(f)
    f.seek(0)
end

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

current_file = open(input_file)

puts "First let's print the whole file:¥n"

print_all(current_file)

puts "Let's rewind kind a like a tape"

rewind(current_file)

puts "Let's print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

I'm sure there is a kinda similar post to this, but my question is a bit different. As seen above, the print_a_line method got two params that are line_count and f.

1) As I understood, line_count argument only serves as a variable which is current_line and it is just an integer. How does it relate to the rewind(f) method because when I run the code, the method print_a_line shows this:

1, Hi
2, I'm a noob

where 1 is the first line and 2 is the second. line_count is just a number, how does ruby know that 1 is line 1 and 2 is line 2?

2) Why use gets.chomp in method print_a_line? If I pass just f like this

def print_a_line(line_count, f)
    puts "#{line_count}, #{f}"
end

I'll get a crazy result which is

1, #<File:0x007fccef84c4c0>
2, #<File:0x007fccef84c4c0>

Because IO#gets reads next line from readable I/O stream(in this case it's a file) and returns a String object when reading successfully and not reached end of the file. And, chomp removes carriage return characters from String object.

So when you have a file with content such as:

This is file content.
This file has multiple lines.

The code will print:

1, This is file content.
2, This file has multiple lines.

In the second case, you're passing file object itself and not reading it. Hence you see those objects in output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM