Andy - 6 months ago 45

Ruby Question

First post here. I'll cut to the chase: why does this method work? I've been staring at it for the last hour trying to make sense of it, but I think what's confusing me is that there are just tons of variables.

Can anybody help explain it to me, perhaps line by line? Assume that **is_prime?(i)** is a previous method that tests if a certain number is a prime number. Thank you!

`def nth_prime(n)`

prime_num = 0

i = 2

while true

if is_prime?(i)

prime_num += 1

if prime_num == n

return i

end

end

i += 1

end

end

Answer

Renaming some variables and starting at `current_number == 0`

to make it clear we're going through every number one by one.

```
def nth_prime(n)
prime_count = 0 #keeps track of how many primes we have so far
current_num = 0 #current number we will go from 0..n
while true
if is_prime?(current_num)
prime_count += 1
if prime_count == n
return current_num
end
end
current_num += 1
end
end
```

As I say, we're going through all the numbers from `0`

to `n`

using a **while-loop** and `current_num += 1`

.

If the `current_num`

is prime our `prime_count`

goes up by 1 which corresponds to the 1st prime etc. If the `prime_count`

is then also equal to `n`

we return `current_num`

which will be the nth prime.