以下是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)
中,f
是File
类型的对象。 File
是IO
的子类。来自IO
的{{1}}的实施定义如下:
seek
有两个参数(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_
和amount
)而不是一个。在这种情况下,第二个参数是可选的(我可以从这个定义中说出来)吗?或者Ruby使用另一种whence
方法(不是来自seek
)?在那种情况下,从哪个类?
答案 0 :(得分:1)
您可以从定义中判断参数是否可选。如果后跟=
和表达式,则该参数是可选的,该值是默认值。在这种情况下,whence
是可选的。
要确定使用层次结构中的哪个定义,请使用owner
。
f.method(:seek).owner
将返回使用其定义的模块。