What is the "=~" operator in Ruby?

CCSab picture CCSab · Jun 11, 2010 · Viewed 20.1k times · Source

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.

Answer

ealdent picture ealdent · Jun 11, 2010

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.