On 2/9/06, James B. Byrne <ByrneJB / hartelyne.ca> wrote:
> I am using Regexp.new() and my unit test alters behaviour for the same
> regexp string depending upon whether or not any option is added to the
> call.

The key is the difference here:

> Thus f_nam_re = Regexp.new(f_nam_re_s) produces this:
> The regexp used is:
> /^QPCCCMR[[:digit:]]$/

> whereas f_nam_re = Regexp.new(f_nam_re_s, ["m") produces this:
> The regexp used is:
> /^QPCCCMR[[:digit:]]$/i

The second regex is coming out case insensitive (and not multiline).
To see why this is, check the Regex documentation[1]. The second
parameter to Regexp.new needs to be a Fixnum (ie. integer). Otherwise,
any other non-nil value (so "m" counts) simply switches the regex to
case-insensitive. What you want to use instead of "m" is
Regexp::MULTILINE[2], eg.:

  f_nam_re_s = "^QPCCCMR[[:digit:]]$"
  f_nam_re = Regexp.new(f_nam_re_s, Regexp::MULTILINE)
  # => /^QPCCCMR[[:digit:]]$/m

Another alternative is to simply build it using the regexp literal syntax:

  f_nam_re_s = "^QPCCCMR[[:digit:]]$"
  f_nam_re = /#{f_nam_re_s}/m
  # => /^QPCCCMR[[:digit:]]$/m

As you can see, string interpolation works fine in the literal syntax.

Jacob Fugal

[1] http://www.ruby-doc.org/core/classes/Regexp.html#M001526
[2] This used to be Regexp::POSIXLINE in 1.6