Ruby/Development/Match Operator

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

match operator demo

puts name = "this is a test" 
puts name =~ /a/ # 1 
puts name =~ /z/ # nil 
puts /a/ =~ name # 1



match operators return the character position at which the match occurred.

$& receives the part of the string that was matched by the pattern, 
$` receives the part of the string that preceded the match
$" receivesthe string after the match. 
 
def show_regexp(a, re) 
    if a =~ re 
        "#{$`}<<#{$&}>>#{$"}" 
    else 
        "no match" 
    end 
end 
 
puts show_regexp("very interesting", /t/) 
puts show_regexp("this is a test", /a/) 
puts show_regexp("these are all tests", /ll/)
puts show_regexp("zeller", /z/)