[Ruby] [Ruby] What is !! used for after all?

1 minute read


It feels uncomfortable to use even though I feel like I’m not lost.

I will write it with my own interpretation that I looked up and saw

####! is a logical operator

Logical operators are operators that return true or false

There are other logical operators such as and and or.

! evaluates the object

Returns true if nil or false

if true returns false

That is !

That is, the negative logical operator


irb(main):018:0> !nil
=> true
irb(main):019:0> !false
=> true
irb(main):020:0> !true
=> false

####~~!! is a negation negation logical operator ~~

*@scivola-san commented that there is no single logical operator !!, so the above may not be the proper expression. Thank you for correcting it! Thank you! *

What is ####!!

By repeating ! twice, the true or false returned by the first ! is denied once again.

Returns false if nil or false

returns true if true

In other words, you’re making a negative denial.


irb(main):025:0> !!false
=> false
irb(main):026:0> !!nil
=> false
irb(main):027:0> !!true
=> true

Well, I don’t know what I’m going to use it for just this.

Not lost? Do you call it a feeling of strangeness when you use Japanese like this?

The answer is a logical operator. Was that

Logical operators evaluate and return a boolean object (true,false)

Of course, not all objects return a boolean object.

irb(main):001:0> a = "a"
=> "Ah"
irb(main):002:0> a
=> "Ah"

So if you want true or false and write without !! it will look like this

irb(main):028:0> a = "a"
=> "Ah"
irb(main):029:0> a ?true :false
=> true

But if you use !!

irb(main):031:0> a = "a"
=> "Ah"
irb(main):032:0> !!a
=> true

With this, you can call in two letters! Great smart! !!

This is the merit that I think!