Numeric not operator trick

610 views

What is the return value of the following Ruby code?

(42 + 0.42).!@.!@ # => ???

The correct answer is

42.42

It raises SyntaxError

true

false

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

(42 + 0.42).!@.!@

is equivalent to

!!(42 + 0.42)

The Double Negation idiom

Here's an interesting and somewhat popular idiom used to convert a value to a boolean (true or false).

This idiom is called Double Negation.

Let's see how it works:

!!42  # => true
!!nil # => false

!!true  # => true
!!false # => false

The code might look a bit mysterious, but once you realize that !@ is just a regular method in Ruby, double negation is essentially a shortcut for:

(42 + 0.42).!@.!@

It's crucial to note that !! is not some special operator; it's simply two negations combined. Some people find this confusing, so I wanted to clarify it here.

The !@ Unary operator

Calling 42.!.! is similar to calling 42.!@.!@, which is also similar to !!42.

They all invoke the BasicObject#!@ method.

The !@ is a convention to indicate that it's a unary method.

Here @ represents the receiver.

By convention, this lets other developers know that it's a unary method.

Resource

Unary operators in Ruby

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 ©