簡體   English   中英

在Ruby文件對象中尋找方法

[英]Seek method in ruby File object

這是Zed Shaw的書中的一些代碼:

input_file = ARGV[0]
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.readline()}"
end

current_file = File.open(input_file)

puts "First Let's print the whole file:"
puts # a blank line

print_all(current_file)

puts "Now Let's rewind, kind of like a tape"

rewind(current_file)

puts "Let's print the first line:"

current_line = 1
print_a_line(current_line, current_file)

rewind(f)fFile類型對象。 FileIO的子類。 從實現IOseek定義這樣的:

seek(amount, whence=IO::SEEK_SET) → 0
Seeks to a given offset anInteger in the stream according to the value of whence:

:CUR or IO::SEEK_CUR  | Seeks to _amount_ plus current position
----------------------+--------------------------------------------------
:END or IO::SEEK_END  | Seeks to _amount_ plus end of stream (you
                      | probably want a negative value for _amount_)
----------------------+--------------------------------------------------
:SET or IO::SEEK_SET  | Seeks to the absolute location given by _amount_

有兩個參數( amountwhence ),而不是一個。 在那種情況下,第二個參數是可選的(我不能從這個定義中看出)嗎? 還是Ruby使用其他seek方法(不是來自IO )? 在那種情況下,來自哪個班級?

您可以從定義中判斷參數是否可選。 如果其后跟=和一個表達式,則該參數是可選的,該值為默認值。 在這種情況下, whence是可選的。

要確定使用了層次結構中的哪個定義,請使用owner

f.method(:seek).owner

將返回使用其定義的模塊。

暫無
暫無

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

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