0
votes

Here's the problem: "Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”."

My code below works, but I don't understand why, on the last line, it is f || b and not f & b?

Shouldn't both f AND b have to be truth in order to return FizzBuzz, not f OR b?

puts (1..100).map {|i|
  f = i % 3 == 0 ? 'Fizz' : nil
  b = i % 5 == 0 ? 'Buzz' : nil
  f || b ? "#{ f }#{ b }" : i
}
1
How did you manage to write working code that you don't understand? - Blorgbeard
Just work through the code on paper for values of i like 3, 5, 15, and 1. - millimoose
I tried & first, because I thought it would work. Then I tried || and it worked. That's how I managed. - hopheady
Note that & is not a companion to ||, && is. (& is bitwise and, not boolean and. Its companion is |.) - Andrew Marshall

1 Answers

3
votes

f || b is true if f is not null or b is not null, or both, because that's part of the definition of OR.

If that expression is true, then we print "#{ f }#{ b }", which will print either Fizz, Buzz, or FizzBuzz depending on whether f or b (or neither) are null, since a null variable will be replaced with a blank string.