From: Albert Schlef Date: 2010-02-05T22:01:14+09:00 Subject: Re: Some noob questions Robert Klemme wrote: > 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):002:1> def self.foreach > irb(main):003:2> if block_given? > [...] > irb(main):007:3> else > irb(main):008:3* Enumerator.new(self, :foreach) > irb(main):009:3> end > irb(main):010:2> end Nice. Pheeew, I still have a long road to walk before I acquire the "Ruby way of thinking". Robert, thanks. Whenever I read your answers here, even to the most trivial questions, I'm treated to some eye-opening gems. I'm generally aware of the power of Ruby, but oftentimes it seems to me unleashing it would involve a few lines of code, whereas you do it easily in just one line of it. -- Posted via http://www.ruby-forum.com/.