Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Ruby use =~ instead of ~= for matching operator?

Tags:

regex

ruby

I have this stupid question about matching operator in Ruby. Why did Ruby make the matching operator =~ instead of ~=? Is there a historical, psychological or other considerations of making the former instead of the later?

I couldn't found any info on this, and I need to make sense about this because I keep typing the wrong thing due to other operator such as +=, -=, !=, >= and <= place the = on the right of the other operator, while =~ is the opposite.

Please enlight me.

like image 344
O.O Avatar asked May 07 '26 18:05

O.O


2 Answers

My opinion is that it is more consistant. They are several 'equal' and 'match' operators. For instance:

=~ for 'matches'

!~ for 'does not match'

== for 'equals'

!= for 'does not equal'

like image 135
Thomas Avatar answered May 09 '26 07:05

Thomas


Also from a far higher level prospective if you think about the way you would read these symbols in words it makes prefect sense:

  • += -= are basically saying a = a + b or a = a - b obviously the addition(+) or subtraction(-) must happen prior to the assignment(=).
  • As for comparison operators like >= != these make sense too because you are asking is a greater than(>) or equal to(=) bor does a not(!) equal(=) b so why not write it that way.
  • In the same way ~= would be like saying does a pattern(~) match(=) b when what you want is =~ which would read does a match(=) pattern(~) b.

If you read them as words it become fairly succinct.

like image 25
engineersmnky Avatar answered May 09 '26 06:05

engineersmnky