Reputation: 33
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
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.
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
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
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
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