Ruby - String match method


=~ returns the position of the first match or nil depending on whether the regular expression matches the string.

String match method provides a lot more power.


puts "String has vowels" if "This is a test".match(/[aeiou]/)


In regular expressions, if you surround a section of the expression with parentheses ( and ), the data matched is made available separately from the rest.

match method lets you access this data:


x = "This is a test".match(/(\w+) (\w+)/) 
puts x[0] # from   ww w.  ja  v a 2s .  co  m
puts x[1] 
puts x[2]


match method returns a MatchData object that can be accessed like an array.

The first element (x[0]) contains the data matched by the entire regular expression.

Related Topic