The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Ruby's Hidden do {} while () Loop

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Jeremy Voorhis

Posts: 212
Nickname: jvoorhis
Registered: Oct, 2005

Jeremy Voorhis is a Rubyist in northeast Ohio.
Ruby's Hidden do {} while () Loop Posted: Jun 12, 2007 5:37 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Jeremy Voorhis.
Original Post: Ruby's Hidden do {} while () Loop
Feed Title: JVoorhis
Feed URL:
Feed Description: JVoorhis is a Rubyist in northeast Ohio. He rambles about Ruby on Rails, development practices, other frameworks such as Django, and on other days he is just full of snark.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Jeremy Voorhis
Latest Posts From JVoorhis

I found the following snippet while reading the source for Tempfile#initialize in the Ruby core library:

  tmpname = File.join(tmpdir, make_tmpname(basename, n))
  lock = tmpname + '.lock'
  n += 1
end while @@cleanlist.include?(tmpname) or
  File.exist?(lock) or File.exist?(tmpname)
At first glance, I assumed the while modifier would be evaluated before the contents of begin...end, but that is not the case. Observe:

>> begin
?>   puts "do {} while ()" 
>> end while false
do {} while ()
=> nil
As you would expect, the loop will continue to execute while the modifier is true.

>> n = 3
=> 3
>> begin
?>   puts n
>>   n -= 1
>> end while n > 0
=> nil
While I would be happy to never see this idiom again, begin...end is quite powerful. The following is a common idiom to memoize a one-liner method with no params:

def expensive
  @expensive ||= 2 + 2
Here is an ugly, but quick way to memoize something more complex:

def expensive
  @expensive ||=
      n = 99
      buf = "" 
        buf << "#{n} bottles of beer on the wall\n" 
        # ...
        n -= 1
      end while n > 0
      buf << "no more bottles of beer" 

Read: Ruby's Hidden do {} while () Loop

Topic: The erubycon Interviews: Bruce Tate Answers Previous Topic   Next Topic Topic: Looking for a good laptop for Ruby development

Sponsored Links


Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use