Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby operator "=~" [duplicate]

Tags:

operators

ruby

People also ask

What does =~ mean in Ruby?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What is << in Ruby on Rails?

It lets you add items to a collection or even concatenate strings.

How do you use the operator in Ruby?

Add AND Assignment (+=) operator is used for adding left operand with right operand and then assigning it to variable on the left. Subtract AND Assignment (-=) operator is used for subtracting left operand with right operand and then assigning it to variable on the left.


The =~ operator matches the regular expression against a string, and it returns either the offset of the match from the string if it is found, otherwise nil.

/mi/ =~ "hi mike" # => 3 
"hi mike" =~ /mi/ # => 3 

"mike" =~ /ruby/ # => nil 

You can place the string/regex on either side of the operator as you can see above.


This operator matches strings against regular expressions.

s = 'how now brown cow'

s =~ /cow/ # => 14
s =~ /now/ # => 4
s =~ /cat/ # => nil

If the String matches the expression, the operator returns the offset, and if it doesn't, it returns nil. It's slightly more complicated than that: see documentation here; it's a method in the String class.


=~ is an operator for matching regular expressions, that will return the index of the start of the match (or nil if there is no match).

See here for the documentation.