File.open and each

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

···

On Tue, May 6, 2014 at 9:23 AM, gvim <gvimrc@gmail.com> wrote:

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

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/001-Using_blocks_for_Robustness.html
http://blog.rubybestpractices.com/posts/rklemme/002_Writing_Block_Methods.html

Kind regards

robert

···

On Tue, May 6, 2014 at 6:23 PM, gvim <gvimrc@gmail.com> wrote:

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?

--
[guy, jim].each {|him| remember.him do |as, often| as.you_can - without end}
http://blog.rubybestpractices.com/