On Tue, 20 Sep 2005, Gergely Kontra wrote:

> Hi!
>
> Is there a similar construct to python's:
>
>>>> for n in range(2, 10):
> ...     for x in range(2, n):
> ...         if n % x == 0:
> ...             print n, 'equals', x, '*', n/x
> ...             break
> ...     else:
> ...         # loop fell through without finding a factor
> ...         print n, 'is a prime number'
> ...
> 2 is a prime number
> 3 is a prime number
> 4 equals 2 * 2
> 5 is a prime number
> 6 equals 2 * 3
> 7 is a prime number
> 8 equals 2 * 4
> 9 equals 3 * 3

i would probably use catch/throw:

   harp:~ > cat a.rb
   (2 ... 10).each do |n|
     x = catch('x'){(2 ... n).each{|x| throw 'x', x if n % x == 0}; nil}
     if x
       puts "#{ n } = #{ n } * #{ x }/#{ n }"
     else
       puts "#{ n } is prime"
     end
   end


   harp:~ > ruby a.rb
   2 is prime
   3 is prime
   4 = 4 * 2/4
   5 is prime
   6 = 6 * 2/6
   7 is prime
   8 = 8 * 2/8
   9 = 9 * 3/9

cheers.

-a
-- 
===============================================================================
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| Your life dwells amoung the causes of death
| Like a lamp standing in a strong breeze.  --Nagarjuna
===============================================================================