Bogdan
Bogdan

Reputation: 33

I don't understand what is wrong with this "if" statement

I have a simple program and I don't understand what is the problem.

(1..100).each do|i|
  if(i%3 == 0)
    puts "Fizz"
  elsif(i%5 == 0)
    puts "Buzz"
  elsif((i%5 == 0) && (i%3 == 0))
    puts "FizzBuzz"
  else
    puts "#{i}"
  end
end

Everything is working except for the numbers that are divisible by both 5 and 3.

When I run the program I get

1,2,Fizz,4,Buzz,.......,14,Fizz,...

What is the problem?

Upvotes: 0

Views: 53

Answers (4)

Makoto
Makoto

Reputation: 106528

There's a slightly more straightforward way to do it, without the need to check for all cases.

Create an array and place your resulting string there.

  • If the number is divisible by 3, append Fizz to the array.
  • If the number is divisible by 5, append Buzz to the array.
    • Note in doing this, if we have a number divisible by 3 and 5, we append Fizz and Buzz to the array.
  • If we haven't pushed anything at all to the array, append the numeral instead.
  • Join all elements of the array and print that instead.

Here's a snippet.

def fizzbuzz
  (1..100).each do|i|
    r = []
    if(i % 3 == 0)
      r << "Fizz"
    end
    if(i % 5 == 0)
      r << "Buzz"
    end
    if r.empty?
      r << i
    end
    puts r.join
  end
end

Upvotes: 0

Beirdo
Beirdo

Reputation: 424

If it is divisible by both 3 and 5, an earlier if/elsif would catch it. That line should not be an elsif, it should be an if, or you need to test it before the individual parts.

Basically, the logic flow is incorrect.

Upvotes: 1

Edward Manda
Edward Manda

Reputation: 579

You misunderstand that once the condition in if is met, it doesn't bother to check the rest of the conditions.

One clever way is to use mod 15 in this case like:

(1..100).each do|i|
  if(i%15 == 0)
     puts "FizzBuzz"
  elsif(i%3 == 0)
    puts "Fizz"
  elsif(i%5 == 0)
    puts "Buzz"
  else
    puts "#{i}"
  end
end

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122503

Every number that is divisible with 5 and 3, note that they make the condition if (i%3 == 0) true first. So the elsif((i%5 == 0) && (i%3 == 0)) is never entered.

A simple fix is to check ((i%5 == 0) && (i%3 == 0)) first.

Upvotes: 1

Related Questions