From: Tim Hammerquist Date: 2005-09-20T18:31:37+09:00 Subject: Re: ruby idiom for python's for/else while/else Joe Van Dyk wrote: > William Morgan wrote: > > Excerpts from Gergely Kontra's mail of 19 Sep 2005 (CDT): > > > >>> 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. > > Meh, I think the Python version is much clearer. Each to his > own, I guess. I agree that the Python construct is clearer... *if* you're familiar with the for...else construct. There are occasions where this construct is very useful, but it seems to be a slight contradiction to Python's motto of "There should be one -- and preferably only one -- obvious way to do it." Tim Hammerquist