From: Robert Klemme Date: 2010-02-05T21:06:58+09:00 Subject: Re: Some noob questions On 02/05/2010 12:50 PM, Albert Schlef wrote: > Robert Klemme wrote: >> On 05.02.2010 00:10, Albert Schlef wrote: >>> Robert Klemme wrote: >>>> File.foreach(file).each_slice 2 do |name, pwd| >>> How is it better than 'File.open(file).each_slice' ? >> It closes the file handle properly which your variant doesn't do. > > You mean, that in my version the file isn't closed till the file object > gets destroyed by the garbage collector? Exactly. > I see. > > (I assume the enumerator returned by foreach() mimics foreach()'s > behaviour; that is, that it closes the file after the last iteration.) It does not _mimic_ the behavior, it _uses_ it!! irb(main):001:0> class X irb(main):002:1> def self.foreach irb(main):003:2> if block_given? irb(main):004:3> puts "open" irb(main):005:3> yield 123 irb(main):006:3> puts "close" irb(main):007:3> else irb(main):008:3* Enumerator.new(self, :foreach) irb(main):009:3> end irb(main):010:2> end irb(main):011:1> end => nil irb(main):012:0> X.foreach {|x| p x} open 123 close => nil irb(main):013:0> X.foreach.map {|x| x + 10000} open close => [10123] irb(main):014:0> Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/