Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the ==~ operator do?

What does the ==~ operator do as in the following?

['a','b','c'].join ==~ /b/
# =>false

I tried a few different arrays and strings and never received a syntax error, but ==~ seems to be a regex comparison operator that always returns false.

like image 347
Sqeaky Avatar asked Oct 29 '25 20:10

Sqeaky


2 Answers

You're right that ==~ is actually == and ~ but a unary ~ has a different meaning for a regex that you think it does. From the fine manual:

~ rxp → integer or nil

Match—Matches rxp against the contents of $_. Equivalent to rxp =~ $_.

$_ = "input data"
~ /at/   #=> 7

Generally you'd use ~regex in a command line one liner that uses one of the switches that wraps your Ruby in an implicit loop and sets $_.

Consider this simple example and you'll see what's going on:

>> $_ = 'pancakes'
=> "pancakes"
>> ~/pancakes/
=> 0
>> 0 ==~ /pancakes/
=> true
like image 126
mu is too short Avatar answered Nov 01 '25 14:11

mu is too short


This is actually two different operators == and ~. ~ is a bitwise not or bitwise complement operator. When used against a regular expression it always evaluates to nil. I think this is because regular expressions do not have a meaningful bitwise pattern.

>~/b/
=> nil

When you compare nil to anything (except nil) you get false.

>a=60
=> 60
> ~a
=> -61

If you have a variable a and it is storing 60 as a Fixnum, on x86 its actually storing 00111100. In this case ~a returns the value represented by 11000011, -61.

like image 39
2 revs, 2 users 92%Sqeaky Avatar answered Nov 01 '25 13:11

2 revs, 2 users 92%Sqeaky