File.open and blocks in Ruby 1.8.7

I'm new to ruby, and now I'm reading Pickaxe's book to get to know everything. I came across the File.open section, which discusses the issue of taking a block as a parameter in a call to File.open, which ensures that the file is closed. Now that sounds like a completely brilliant way to avoid shooting in the leg, and since I'm dangerously low on my toes, I suppose I'll give it back. Here is what I wrote (in irb, if that matters):

File.open('somefile.txt', 'r').each { |line| puts line }`` 

I expected the somefile.txt file somefile.txt be open, read, printed, and closed, right? As far as I can tell is wrong. If I use lsof to view open file descriptors, it will still be open. However, if I do

 f = File.open('somefile.txt', 'r').each { |line| puts line } f.close() 

I use the blocks in this example incorrectly or I could not understand the value of File.open when used with a block. I read the ruby-doc.org section related to File.open , but that seems to confirm that I am working as expected.

Can someone explain what I'm doing wrong?

+6
source share
1 answer

To close the file after the block, you must pass the File.open() block directly, not each :

 File.open('somefile.txt', 'r') do |f| f.each_line { |l| puts l } end 

File.open(…).each {…} just File.open(…).each {…} over the open file without closing it.

+8
source

Source: https://habr.com/ru/post/893617/


All Articles