Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between "!=" and "!~" in Ruby?

Tags:

ruby

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?

 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 ?

like image 494
Arup Rakshit Avatar asked Jan 22 '26 20:01

Arup Rakshit


1 Answers

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.

like image 129
jtbandes Avatar answered Jan 24 '26 13:01

jtbandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!