I have 2 questions : 1 - I don't understand meaning of thing that , this code return :
File.open("a.txt") do |i|
puts i
end
please explain me.
2 - and please explain me what is the difference between that code and below code :
File.open("a.txt").each do |i|
puts i
end
thanks
With:
File.open( "some_file.txt" ) do |file|
puts file.read
end
The open method calls your block with a File instance and cleans up the file reference once your block returns, closing and flushing the file as needed, so your application does not leak file handlers, which is awesome as we usually forget to close files or do not take into account that file handling might yield exceptions.
When you do it like this:
file = File.open("some_file.txt")
puts file.read
The open method gives you the File instance but now you are responsible for cleaning up the mess and closing the file when you don't need it anymore. So, if you're doing it like this, you should possibly set the file into a begin/rescue block and add an ensure clause closing the file if anything goes wrong.
Unless you have a very specific need, you should never use this second version, the first version is simpler and safer and you don't have to care about closing/cleaning up whatever you did to the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With