From: Eric Mahurin Date: 2005-09-20T11:35:51+09:00 Subject: Re: ruby idiom for python's for/else while/else --- why the lucky stiff wrote: > William Morgan wrote: > > >Excerpts from Gergely Kontra's mail of 19 Sep 2005 (CDT): > > > > > >>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' > >>... > >> > >> > > > >I don't think there's a direct idiom. I'd write this in Ruby > as: > > > >(2...10).each do |n| > > fac = (2...n).find { |x| n % x == 0 } > > if fac > > puts "#{n} equals #{fac} * #{n / fac}" > > else > > puts "#{n} is a prime number" > > end > >end > > > >This is much clearer IMO. > > > Yeah, this isn't any clearer, but here's one that > demonstrates the > possibilities in tying iterators and conditionals together. > It works > because `break' causes the iterator to return nil. > > for n in 2...10 > puts "#{ n } is a prime number" if > for x in 2...n > if n % x == 0 > puts "#{ n } equals #{ x }*#{ n/x }" > break > end > end > end > > _why This is annoying - builtin loops and "loop" returns nil whereas many of the object method loops (for..in is just the each method) return the object. Using a builtin loop, you can do something like this to get something much closer to python's while/else (becomes while/or in ruby): (2...10).each do |n| x = 2 while x