Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Jan 17 ’12

The =~ and !~ operators

The operator =~ matches a String against a regular expression pattern. It returns the position/index where the String was matched - or nil if no match was found:

/Quick/ =~ "Ruby Quicktips"
# => 5

# Order does not matter
"Ruby Quicktips" =~ /Quick/
# => 5

"Ruby Quicktips" =~ /foo/
# => nil

Because it returns nil when no match is found, you can for example use this as a condition in if-statements:

if "Ruby Quicktips" =~ /\s+/
  puts "The string contains at least one whitespace character."
end
# The string contains at least one whitespace character.
# => nil

To check the opposite, you can use the !~ operator:

if "Ruby Quicktips" !~ /\d+/
  puts "The string does not contain any digits."
end
# The string does not contains any digits.
# => nil

8 notes 0 comments

  1. jaredengler reblogged this from rubyquicktips
  2. haru012 reblogged this from rubyquicktips
  3. rubyquicktips posted this

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus