簡體   English   中英

傳遞gets.chomp作為參數

[英]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)

我敢肯定有類似的帖子,但是我的問題有點不同。 如上所示,print_a_line方法有兩個參數,分別是line_count和f。

1)據我了解,line_count參數僅用作變量current_line,並且它只是一個整數。 它與rewind(f)方法有什么關系,因為當我運行代碼時,方法print_a_line顯示如下:

1, Hi
2, I'm a noob

其中1是第一行,2是第二行。 line_count只是一個數字,ruby如何知道1是第1行而2是第2行?

2)為什么在方法print_a_line中使用gets.chomp? 如果我像這樣通過

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

我會得到一個瘋狂的結果是

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

因為IO#gets從可讀的I / O流(在本例中為文件)中讀取下一行,並在成功讀取但未到達文件末尾時返回String對象。 並且, chompString對象中刪除回車符。

因此,當您擁有內容如下的文件時:

This is file content.
This file has multiple lines.

該代碼將打印:

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

在第二種情況下,您要傳遞文件對象本身而不讀取它。 因此,您會在輸出中看到那些對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM