Reputation: 22064
I have a question about Block, do the two codes mean the same?
code 1
File::open('yozloy.txt','w') do |f|
f << 'Some contains'
end
code 2
newFile = File::open('yozloy.txt','w')
newFile << 'Some contains'
Upvotes: 34
Views: 11790
Reputation: 12830
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 ;-)
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.
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.
Upvotes: 33
Reputation: 92335
No, they do not mean the same. In the first example, the file is automatically closed after the block was processed. In the second example, it's your responsibility to manually call newFile.close
.
Upvotes: 43