在Ruby 1.8.7中的File.open和块 [英] File.open and blocks in Ruby 1.8.7

查看:151
本文介绍了在Ruby 1.8.7中的File.open和块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对红宝石很新,而且我正在阅读Pickaxe书来熟悉一切。我遇到了File.open部分,它讨论了如何将块作为File.open调用的参数,然后确保文件已关闭。现在,这听起来像是一个绝妙的方法,以避免在脚下射击自己,而且我的脚趾头很危险,我想我会放弃它。这里是我写的(在irb中,如果重要的话):

pre $ File $ open放在一个文件中, ).each {| line | puts line}``

我的期望是文件 somefile.txt 会被打开,阅读,打印和关闭,对吧?据我可以说错了。如果我使用 lsof 查看打开的文件句柄,它仍然是打开的。然而,如果我这样做的话,那么我们就可以使用这个函数来实现这个功能了:

  f = File.open('somefile.txt','r')。 |在这个例子中,我使用了错误的块吗?或者,我没有理解File.open在与块一起使用时的含义。我已阅读 ruby​​-doc。 org与File.open相关,但似乎证实我所做的工作应该按预期工作。 



任何人都可以解释我做错了什么?

解决方案

为了关闭块之后的文件,您应该将块传递给 File.open() 直接,而不是每个

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

File.open(...)每个{...} 只是迭代打开的文件而不关闭它。


I'm pretty new to ruby and I'm currently reading the Pickaxe book to get familiar with everything. I came across the File.open section where it discusses taking a block as a parameter to a File.open call then guaranteeing that the file is closed. Now this sounds like an absolutely brilliant way to avoid shooting yourself in the foot and as I'm dangerously low on toes, I figure I'll give it a go. Here is what I wrote (in irb if that matters):

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

My expectation was that the file somefile.txt would get opened, read, printed and closed, right? As far as I can tell wrong. If I use lsof to look at open file handles, it's still open. However, if I do

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

Am I using blocks wrong in this example or have I failed to understand the meaning of File.open when used with a block. I've read section on ruby-doc.org related to File.open but that just seems to confirm that what I'm doing ought to be working as expected.

Can anyone explain what I'm doing wrong?

解决方案

In order to close file after block, you should pass block to File.open() directly, not to each:

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

File.open(…).each {…} is just iterating over opened file without closing it.

这篇关于在Ruby 1.8.7中的File.open和块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆