I’m running through the problems on Project Euler to teach myself Ruby programming. I know there is a built-in function to do this, but I’m avoiding the built-in functions to help me learn.
So I have to write a method to determine if a number is a prime. The first method works, but the second doesn’t. Can anyone explain why?
def is_prime n
for d in 2..(n - 1)
if (n % d) == 0
return false
end
end
true
end
def is_prime2 n
foundDivider = false
for d in 2..(n - 1)
foundDivider = ((n % d) == 0) or foundDivider
end
not foundDivider
end
It’s because
=is of higher precedence thanor. See Ruby’s operator precedence table below (highest to lowest precedence):The problematic line is being parsed as…
…which is certainly not what you mean. There are two possible solutions:
Force the precedence to be what you really mean…
…or use the
||operator instead, which has higher precedence than=: