File.open 带块 vs 不带 [英] File.open with block vs without
问题描述
我有一个关于 Block 的问题,这两个代码的意思一样吗?
I have a question about Block, do the two codes mean the same?
代码 1
File::open('yozloy.txt','w') do |f|
f << 'Some contains'
end
代码 2
newFile = File::open('yozloy.txt','w')
newFile << 'Some contains'
推荐答案
DarkDust 已经说过,这些方法是不同的.我会再解释一下这些块,因为我想我能猜到你问这个问题的原因;-)
DarkDust already said that these methods are different. I'll explain you the blocks a little more, as I suppose that I can guess why you asked this question ;-)
ruby 中的块只是某些方法的参数.这不仅仅是一种不同的语法.
The block in ruby is just a parameter for some method. It's not just a different syntax.
接受(可选)块的方法通常有一个条件来测试它们是否被块调用.
Methods which accept (optional) blocks usually have a condition to test whether they have been called with block, or without.
考虑这个非常简单的例子:(真正的 File.open 是类似的,但它确保文件关闭,即使你的块引发错误,例如)
Consider this very simplified example: (the real File.open is similar, but it ensures the file is closed even if your block raises an error, for example)
def open(fname)
self.do_open(fname)
if block_given?
yield(self) # This will 'run' the block with given parameter
self.close
else
return self # This will just return some value
end
end
一般来说,每种方法在有块或没有块的情况下工作(工作)可能不同.应始终在方法文档中说明.
In general, every method may work (works) differently with a block or without a block. It should be always stated in the method documentation.
这篇关于File.open 带块 vs 不带的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!