Reputation: 275
I have a very basic question about Ruby loops.
This program as written returns the ith prime number +1 (ie the example should return 17). I know I could simply return cand-1
, but I was wondering what the "Ruby way" of checking if the answer has been found at the bottom of the while
loop and only incrementing if it hasn't.
def ith_prime(i)
pI = 0 # primes index
divs = []
cand = 2
until pI == i do
if divs.find { |div| cand%div == 0 } == nil
divs << cand
pI += 1
end
cand += 1
end
cand
end
puts ith_prime(7)
> 18
Upvotes: 1
Views: 762
Reputation: 7714
I use loop
instead of while
or until
most of the time. This way I can put the exit condition anywhere in the loop.
I would write it like that (if I understood the problem correctly):
def ith_prime(i)
pI = 0 # primes index
divs = []
cand = 2
loop do
unless divs.find { |div| cand%div == 0 }
divs << cand
pI += 1
end
break if pI == i
cand += 1
end
cand
end
Upvotes: 5