From: Robert Klemme Date: 2010-02-06T03:45:07+09:00 Subject: Re: Some noob questions On 02/05/2010 02:01 PM, Albert Schlef wrote: > 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". Hmm, maybe it helps that I practice a Japanese martial art. ;-) > Robert, thanks. Whenever I read your answers here, even to the most > trivial questions, I'm treated to some eye-opening gems. You're welcome! I'm glad that I could help. I am always amazed how friendly our community is compared to others and I try to maintain that by sharing what I believe to have understood about the language. > 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. Well, it might look easy but of course I don't post all the failed tests and attempts that end in dead end streets in order to not distract from the content I want to convey. :-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/