Re: ruby idiom for python's for/else while/else
- From: "David A. Black" <dblack@xxxxxxxxxxxx>
- Date: Tue, 20 Sep 2005 10:23:44 +0900
Hi --
On Tue, 20 Sep 2005, Jeremy Tregunna wrote:
On 19-Sep-05, at 7:15 PM, 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
Directly, yes; though hardly anybody writes code this way (at least I've never seen anybody write something like this, like how I'm about to give it to you). I'd see William Morgan's message for a better suggestion.
for n in (2..10) do for x in (2..n) do
You'd want the ... range operator, so as to exclude the upper limit.
if n % x == 0
puts "#{n} equals #{x} * #{n/x}"
break
else
puts "#{n} is a prime number"
end
end
end
Have you run it? :-) It doesn't work the same way; it prints "...prime number" for *every* time a match isn't found, until a match is found. So, for example, you get:
7 is a prime number # printed 5 times (2,3,4,5,6) 8 equals 2 * 4 9 is a prime number 9 equals 3 * 3
David
-- David A. Black dblack@xxxxxxxxxxxx
.
- References:
- ruby idiom for python's for/else while/else
- From: Gergely Kontra
- Re: ruby idiom for python's for/else while/else
- From: Jeremy Tregunna
- ruby idiom for python's for/else while/else
- Prev by Date: Re: ruby idiom for python's for/else while/else
- Next by Date: Re: ruby idiom for python's for/else while/else
- Previous by thread: Re: ruby idiom for python's for/else while/else
- Next by thread: Re: ruby idiom for python's for/else while/else
- Index(es):
Relevant Pages
|
Loading