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.
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 torxp =~ $_.$_ = "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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With