Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)
The Prime Directive
An easy method to build and understand is a prime number checker. We want to check to see if a number is prime. Look at the following code:
def is_prime(par)
prime = true
for num in 2...par
if par % num ==0
prime = false
end
end
if prime
puts "Yes"
else
puts "No"
end
end
is_prime(33)
⇩
No
Now we're going to break it down:
Define a method using def.
Give it a name of is_prime.
Give it a parameter name of par.
def is_prime(par)
Create a boolean called prime and set it to true.
def is_prime(par)
prime = true
Create a for loop and run a modulo operation using par with each number between 2 and the number we set as our par.
def is_prime(par)
prime = true
for num in 2...par
if par % num == 0
prime = false
end
end
Explained: If we set par to 8, the first if check will look like this: 8 % 2 = 0. Two goes into eight four times with no remainder. Remember that modulo returns remainders. Here's another: 9 % 2 = 1. Great. We're still in the for loop and now need to check the next number. 9 % 3 = 0. We said if par modulo num is ever equal to zero then set is_prime to false. Let's check a prime number now:
5 % 2 = 1
5 % 3 = 2
5 % 4 = 1
Great! Five must be prime. (We start at 2 because we know 5 % 1 would be zero.)
Moving on. If prime is true, puts "Yes", else puts "No".
def is_prime(par)
prime = true
for num in 2...par
if par % num == 0
prime = false
end
end
if prime #Shorthand for if prime == true
puts "Yes"
else
puts "No"
end
end
is_prime(137) #Check any number here.
⇩
Yes