Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to force non-lazy evaluation of && and || in Ruby?

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))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading