I was trying to play with the operators !~
and !=
in below code. But couldn't figure out such any differences. But I have doubt, If not so, why Ruby introduced them?
我在试着和操作符玩!~和!=在下面的代码中。但无法找出这些差异。但是我怀疑,如果不是,Ruby为什么要引入它们呢?
2 !=3
# => true
2 !~ 3
# => true
c= [1,2,3]
# => [1, 2, 3]
d=[1,4,5]
# => [1, 4, 5]
c != d
# => true
c !~ d
# => true
Could anyone please help me here by saying if any difference between them ?
谁能帮我说一下他们之间有什么区别吗?
1 个解决方案
#1
7
The =~
operator and its negative !~
are for pattern-matching. It is overridden by Regexp and String to provide regular-expression pattern matching, but for numbers it is not implemented. This is why 2 =~ 3
gives nil
, so 2 !~ 3
is true
.
=~运算符及其负值!~用于模式匹配。它被Regexp和String覆盖,以提供正则表达式模式匹配,但是对于数字,它没有实现。这就是为什么2 =~ 3表示nil,所以2 !~ 3是正确的。
#1
7
The =~
operator and its negative !~
are for pattern-matching. It is overridden by Regexp and String to provide regular-expression pattern matching, but for numbers it is not implemented. This is why 2 =~ 3
gives nil
, so 2 !~ 3
is true
.
=~运算符及其负值!~用于模式匹配。它被Regexp和String覆盖,以提供正则表达式模式匹配,但是对于数字,它没有实现。这就是为什么2 =~ 3表示nil,所以2 !~ 3是正确的。