Position Anchors

We'll leave character classes aside for a while, and look at the difference between matching characters and positions. There are times when we want to match a pattern only if it is at a certain place, relative to line or word boundaries.

Line boundaries are specified by the caret (^) and dollar sign ($) characters; these represent the start and end of a line, respectively. So /^Fre/ matches "Freedom's just another word" but not "Cooking with Freya". To make sure what you match is on a line by itself, use both, as in /^INTRODUCTION:$/.

Line boundary matching respects the divisions within a multiline string.

rhyme = "Mary Mary\nQuite contrary"
/ary/   =~ rhyme #-> 1
/ary$/  =~ rhyme #-> 6
/rary$/ =~ rhyme #-> 20

Ruby also recognizes ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.