Forum: Ruby File.open and each

0946b736110f6af95c93bce0ea6d46ff?d=identicon&s=25 Gerald Vim (gvim)
on 2014-05-06 18:24
(Received via mailing list)
What's the difference between:

open('file.txt') {|fh| fh.each {|l| puts l}}

... and:

open('file.txt').each {|l| puts l}

? The first example seems to be favoured in "Well Grounded Rubyist" but
I discovered I could call each directly on the File.open object as it's
enumerable. Any advantages of one over the other?

gvim
60b83bb4579cd684731a1709f85ee849?d=identicon&s=25 John W Higgins (Guest)
on 2014-05-06 18:43
(Received via mailing list)
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (robert_k78)
on 2014-05-06 19:28
(Received via mailing list)
On Tue, May 6, 2014 at 6:23 PM, gvim <gvimrc@gmail.com> wrote:
> enumerable. Any advantages of one over the other?
Yes, you should always use the first form because that ensures the
file handle is closed properly - even in case of exceptions in the
block.

Even simpler is

File.foreach 'file.txt' do |line|
  puts line
end

or if you prefer the other syntax

File.foreach('file.txt') {|line| puts line}

For more details please see also
http://blog.rubybestpractices.com/posts/rklemme/00...
http://blog.rubybestpractices.com/posts/rklemme/00...

Kind regards

robert
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.