What is the !=~ comparison operator in ruby?

后端 未结 2 1622
生来不讨喜
生来不讨喜 2020-12-17 14:25

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 \"

相关标签:
2条回答
  • !~ is the inverse of =~ NOT !=~

    0 讨论(0)
  • 2020-12-17 14:47

    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
    
    0 讨论(0)
提交回复
热议问题