Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "=~" operator in Ruby?

Tags:

operators

ruby

I saw this on a screencast and couldn't figure out what it was. Reference sheets just pile it in with other operators as a general pattern match operator.

like image 615
CCSab Avatar asked Jun 11 '10 20:06

CCSab


People also ask

What are operators in Ruby?

Ruby Arithmetic OperatorsAddition − Adds values on either side of the operator. Subtraction − Subtracts right hand operand from left hand operand. Multiplication − Multiplies values on either side of the operator. Division − Divides left hand operand by right hand operand.

What does << do in Ruby?

you can use the operator << to push a element into an array or to concatenate a string to another. so, what this is this doing is creating a new element/object Thread type and pushing it into the array.

What is << in Ruby on Rails?

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


2 Answers

It matches string to a regular expression.

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

If there is no match, it will return nil. If you pass it invalid arguments (ie, left or right-hand sides are not correct), it will either throw a TypeError or return false.

like image 158
ealdent Avatar answered Sep 19 '22 18:09

ealdent


From ruby-doc :

str =~ obj => fixnum or nil

Match—If obj is a Regexp, use it as a pattern to match against str, and returns the offset position the match starts, or nil if there is no match. Otherwise, invokes obj.=~, passing str as an argument. The default =~ in Object returns false.

"cat o' 9 tails" =~ /\d/   #=> 7 "cat o' 9 tails" =~ 9      #=> false 
like image 38
Ju Nogueira Avatar answered Sep 16 '22 18:09

Ju Nogueira