[英]gets.chomp inside a function in ruby
我正在經歷“以艱難的方式學習Ruby”,而在練習20中,有一段我不理解的代碼片段。 我不明白為什么在函數“print_a_line”中調用f的gets.chomp。
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 "Now let's rewind, kind of like a tape."
rewind(current_file)
puts "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
因此,我不明白輸出的第二部分是如何產生的。 我理解它是傳遞給代碼的test.txt文件的前3行,但我不明白f.gets.chomp是如何產生這一行的。
$ ruby ex20.rb test.txt
First let's print the whole file:
This is line 1
This is line 2
This is line 3
Now let's rewind, kind of like a tape.
Let's print three lines:
1, This is line 1
2, This is line 2
3, This is line 3
File對象f
跟蹤它在文件中讀取的位置(以及它引用的內容跟蹤)。 您可以將其視為在文件中讀取時前進的光標。 當你告訴f
gets
,它會一直讀到它到達新行。 它們的關鍵是f
記住你的位置,因為讀數會提升“光標”。 chomp
call根本不進入這個部分。 因此,每次調用f.gets
只會讀取文件的下一行並將其作為字符串返回。
chomp
只是操作f.gets
返回的字符串,對File對象沒有影響。
編輯:要完成答案: chomp
返回刪除了尾部換行符的字符串。 (從技術上講,它刪除了記錄分隔符,但這幾乎與新行不同。)這來自Perl(AFAIK),其想法是,基本上你不必擔心你的特定輸入形式是否通過了你是否換行符。
如果您查看IO#gets
的文檔 ,您將看到它從IO對象讀取下一行。 您正在調用的Kernel#open
方法將返回具有該方法的IO對象。 #gets
方法實際上是讓你進入下一行。 它與讀取該行返回的字符串上的#chomp
無關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.