I was playing with the FizzBuzz programming exercise this evening, trying out different ways of writing solutions.
One line which I wrote was:
nf = !((ff = i % 3 == 0) || (bf = i % 5 == 0))
nf is "No flag"
ff is "Fizz flag"
bf is "Buzz flag"
Now I know this is horrible style - I have far better solutions to the original problem - but this one also doesn't work because Ruby's lazy evaluation of || expressions means that if i is a multiple of 3, ff is set to true and bf is left as nil (although it is defined because that happens before the evaluation).
What I've been hunting for without success is a way to make Ruby evaluate both sides of the || (or another operator) so that all three flags get their correct values.
Is there a way of doing it in Ruby?
Perhaps you're looking for the |
and &
operators which do not short-circuit.
E.g.:
irb(main):007:0> true | (puts "hello")
hello
=> true
irb(main):008:0>
Documentation here for TrueClass. The same methods exist for FalseClass
.