Pattern Matching

Matching operator

  • Find a matching string
  • //
  • /reg-expr/
  • Operates on $_ by default
  • Can be bound to another variable using =~
  • Returns the position of the matching substring, or nil if it's not found
if myString =~ /apple/  # Search for "apple" in myString
...
end

Substitution

myString.sub(/apple/, 'orange')    # Replace the first occurrence of "apple" with "orange"
myString.gsub(/apple/, 'orange') # Replace every occurrence