我对以下内容感到满意:
def some_def(foo, &block)
puts "block utilized below"
block.call(foo)
end
def some_other_def(bar)
puts "using yield below"
yield bar
puts "and back into the method"
end
所以我学会了将块(和过程)与yield
关键字分开。
但是,我遇到了以下代码:
# ./open_file.rb
class File
def self.open(name, mode, &block)
file = new(name, mode)
return file unless block_given?
yield(file)
ensure
file.close
end
end
当我在 irb 中执行此代码时,参数&block
似乎无关紧要:
irb -r ./file.open.rb
并执行以下操作:
File.open('foo.txt','r') {|f| puts f}
&block
由 in 呈现为可选block_given?
:
return file unless block_given?