Forum: Ruby and each

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
75df9cf7fe727ae3b9f2ebbb24a9b46a?d=identicon&s=25 Gerald V. (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 object as it's
enumerable. Any advantages of one over the other?

John W Higgins (Guest)
on 2014-05-06 18:43
(Received via mailing list)
13d0171c6ee97074d61f182a6e3a9f4e?d=identicon&s=25 Robert K. (robert_k78)
on 2014-05-06 19:28
(Received via mailing list)
On Tue, May 6, 2014 at 6:23 PM, gvim <> 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

Even simpler is

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

or if you prefer the other syntax

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

For more details please see also

Kind regards

This topic is locked and can not be replied to.