530 views
What's the return value of the following Ruby code?
var = !(!!!())
var # => ???
The correct answer is
It raises SyntaxError
true
false
nil
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
Disclaimer: The code snippet shared below is purely for educational and entertainment purposes. It is not intended for use in production environments
!!!()
: 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
.
!()
: The result of the previous operation, which is true
since !!!()
evaluates to true
, is negated again. So, !
will make it false
.
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à!
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©