0

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
}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
hopheady
  • 37
  • 7

1 Answers1

3

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.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272