Ruby: Divisible by 4

Ruby: divisible by 4

Try this:

if i % 4 == 0

This is called the "modulo operator".

Ruby function to check if a number is divisible by five and is even

Even (divisible by two) and divisible by five also means "divisible by ten":

def is_even_and_divisible_by_five?(n)
n % 10 == 0
end

how to create a divisible by method in ruby

There are 3 steps to fix it

  1. Remove 1st if statement,
  2. You should move this: elsif number % 3 == 0 && number % 5 == 0 to 1st step
  3. Add else puts number

it should look like:

def count
numbers = (1..20)
numbers.each do |number|
if number % 3 == 0 && number % 5 == 0
puts "#{number} i am divisible by 3 & 5"
elsif number % 3 == 0
puts "#{number} i am divisible by 3"
elsif number % 5 == 0
puts "#{number} i am divisible by 5"
else
puts number
end
end
end

UPD

Let's add an explanation about these steps:

1st and 3rd steps:
Dividing by 1 always will return 0 as a result, so the first reason is a mistake in logic and the second one is as now we know that this always is 0 we don't need to check it one more time.

2nd step:
When we check for example 3 with elsif number % 3 == 0 it will return true, so next if-statements wouldn't be checked, to fix it we should first add checking for number % 3 == 0 && number % 5 == 0

Thanks to @3limin4t0r, you are right it's always better to explain.

% and / simbols difference in Ruby

division operator / - gives the quotient of the division whatever the remainder of the division is. So you cannot determine if a number is perfectly divisible (remainder = 0) or not perfectly divisible (with non-zero remainder) using a division operator (/).

10 / 3
#=> 3

modulo operator % - gives the remainder of the division. If perfectly divisible, the output is 0, if not-perfectly divisible the output is non-zero value.

10 % 3
#=> 1

In your case number % 3 == 0 is true only if number is divisible by 3 with 0 remainder (i.e if number passed into the method frizzbuzz is a multiple of 3 like -12, -3, 3, 6, 9, etc )

trying to use each method to find divisible numbers and print them

You need to puts inside the each block too. Also, you can just divide by 4 and check if the remainder is 0. No need of 400

range.each do |year|
puts year if year % 4 == 0;
end

The puts year will be executed only if the if condition is satisfied.



Related Topics



Leave a reply



Submit