CHAPTER SIXTEEN
283
To test for a match you can use if and the =~ operator: if_test.rb if /def/ =~ 'abcdef' The above expression evaluates to true if a match is made (and an integer is returned); it would evaluate to false if no match were made (and nil were re-turned): RegEx = /def/ Str1 = 'abcdef' Str2 = 'ghijkl' if RegEx =~ Str1 then puts( 'true' ) else puts( 'false' ) end #=> displays: true if RegEx =~ Str2 then puts( 'true' ) else puts( 'false' ) end #=> displays: false
Frequently, it is useful to attempt to match some expression from the very start of a string; the character ^ followed by a match term is used to specify this. It may also be useful to make a match from the end of the string; the character $ preceded by a match term is used to specify that. start_end1.rb puts( /^a/ =~ 'abc' ) #=> returns 0 puts( /^b/ =~ 'abc' ) #=> returns nil puts( /c$/ =~ 'abc' ) #=> returns 2 puts( /b$/ =~ 'abc' ) #=> returns nil