Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the !=~ comparison operator in ruby?

Tags:

operators

ruby

I found this operator by chance:

ruby-1.9.2-p290 :028 > "abc" !=~ /abc/
 => true

what's this? It's behavior doesn't look like "not match".

like image 352
Lai Yu-Hsuan Avatar asked Oct 07 '11 22:10

Lai Yu-Hsuan


People also ask

How do you do comparisons in Ruby?

In order to compare things Ruby has a bunch of comparison operators. The operator == returns true if both objects can be considered the same. For example 1 == 1 * 1 will return true , because the numbers on both sides represent the same value.

What does === mean in Ruby?

The === (case equality) operator in Ruby.

What is the name of this operator === in Ruby?

Triple Equals Operator (More Than Equality) Our last operator today is going to be about the triple equals operator ( === ). This one is also a method, and it appears even in places where you wouldn't expect it to. Ruby is calling the === method here on the class.

How do you compare two strings in Ruby?

Two strings or boolean values, are equal if they both have the same length and value. In Ruby, we can use the double equality sign == to check if two strings are equal or not. If they both have the same length and content, a boolean value True is returned. Otherwise, a Boolean value False is returned.


1 Answers

That's not one operator, that's two operators written to look like one operator.

From the operator precedence table (highest to lowest):

[] []=
**
! ~ + - [unary]
[several more lines]
<=> == === != =~ !~

Also, the Regexp class has a unary ~ operator:

~ rxp → integer or nil
Match—Matches rxp against the contents of $_. Equivalent to rxp =~ $_.

So your expression is equivalent to:

"abc" != (/abc/ =~ $_)

And the Regexp#=~ operator (not the same as the more familiar String#=~) returns a number:

rxp =~ str → integer or nil
Match—Matches rxp against str.

So you get true as your final result because comparing a string to a number is false.

For example:

>> $_ = 'Where is pancakes house?'
=> "Where is pancakes house?"
>> 9 !=~ /pancakes/
=> false
>> ~ /pancakes/
=> 9
like image 181
mu is too short Avatar answered Oct 11 '22 21:10

mu is too short