What is the "= ~" operator in Ruby?

I saw it on the screencast and could not understand what it was. The fact sheets simply stack it with other operators as a generic pattern matching operator.

+42
operators ruby
Jun 11 2018-10-06T00:
source share
7 answers

Matches a string in a regular expression.

'hello' =~ /^h/ # => 0

If there is no match, nil returned. If you pass invalid arguments to it (i.e., the left or right sides are incorrect), it will either throw a TypeError or return false .

+39
Jun 11 '10 at 20:07
source share
— -

From ruby-doc :

str =~ obj => fixnum or nil

Match-If obj is a Regexp, use it as a template for matching with str and return the offset position that the match starts, or nil if there is no match. Otherwise, it calls obj. = ~ By passing str as an argument. The default value = ~ in the object returns false.

 "cat o' 9 tails" =~ /\d/ #=> 7 "cat o' 9 tails" =~ 9 #=> false 
+15
Jun 11 '10 at 20:17
source share

Well, the link is correct, this is the operator "matches this regular expression".

 if var =~ /myregex/ then something end 
+4
Jun 11 2018-10-06T00:
source share

As mentioned in other answers, =~ is a regular expression vs string match operator.

Note. The operator =~ not commutative

Please pay attention to the note below on the ruby ​​doc website as I only saw the first form

 str =~ regexp 

used in other answers:

Note: str =~ regexp does not match regexp =~ str . Selected rows from the named capture groups are assigned to local variables only in the second case.

Here is the documentation for the second form: link

+4
Sep 15 '15 at 11:43
source share

A string of regular expressions. Here is a detailed list of operators: http://phrogz.net/programmingruby/tut_expressions.html#table_7.1

+1
Jun 11 '10 at
source share

Regular Expression String:

sets true if url = ~ / google.com /

You can read '= ~' as 'matches'.

+1
Jun 13 '10 at 11:33
source share

I believe this is a pattern matching operator used with regex.

-one
Jun 11 '10 at
source share



All Articles