Stacked negations

530 views

What's the return value of the following Ruby code?

var = !(!!!())

var # => ???

The correct answer is

It raises SyntaxError

true

false

nil

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

Disclaimer: The code snippet shared below is purely for educational and entertainment purposes. It is not intended for use in production environments

  1. !!!(): These are empty parentheses () resulting in nil (putnil operation). this nil is then negated to true using !(). Finally, the double-bang operator is applied to true, resulting in true.

  2. !(): The result of the previous operation, which is true since !!!() evaluates to true, is negated again. So, ! will make it false.

  3. var = !(!!!()): This assigns the result of !(), which is false, to the variable var.

Therefore, when you print var, it will output false. So, the output of the code is as follows:

var = !(!!!())

puts var # => false

Even with the clarification that () evaluates to nil, the code remains somewhat cryptic and not very readable or maintainable.

Voilà!

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©