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 object as it’s
enumerable. Any advantages of one over the other?


On Tue, May 6, 2014 at 6:23 PM, gvim [email protected] 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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs