Hi Austin
Austin Z. wrote:
I disagree that either #to_re or #to_rx would be a good name for this
construct.
I don’t feel strongly about the name, though compare #to_f, #to_i, and
#to_s already in the core - I don’t see those as obviously more
‘expressive’ than to_rx, simply more familiar.
After all, #to_s could mean to ‘to_symbol’, and #to_f could mean
‘to_file’, if one were being perverse.
I don’t think I’ve actually ever seen Regexp.compile used, so maybe it
can be repurposed in 1.9 to do this.
Yes, the special constrctor always makes me think it should do something
“special” - perhaps like the /o modifier in perlre. However, I’d prefer
an instance method in String to a new or repurposed class method in
Regexp.
FWIW, I don’t tend to use the construct that Alex did – I tend to
either anchor my strings or insert them in the middle of a larger
regexp, which is why I don’t particularly think that this is a method
that belongs on String.
I also commonly use them anchored within a larger regexp, but it would
still be nicer to be able to write
/before #{str.to_rx} after/
Than to have to wedge a long call to a class function in an interpolated
section.
I suppose the point I’m making is that Strings have a ‘natural’ affinity
to or representation as Regexps - viz their mutually substitutable uses
in #split, #sub and friends, and so it would be nice to make conversion
between the two less unwieldy and verbose.
Regexp seems to me a ‘major’ core class, with its own literal syntax (as
Float, Integer, String, Symbol) etc. I wouldn’t like to make anyone
write “#{an_integer}” to do the work of Integer#to_s, unless they really
wanted to.
I agree there is some ambiguity about the semantics re anchoring -
should #to_rx mean
/#{Regexp.escape(a_string)/
or
/\A#{Regexp.escape(a_string)\z/
The strongest argument for the former is that the latter doesn’t do
anything useful that #== doesn’t already do.
If it’s to be on String, though, it should probably be on a few others
as well (Fixnum) and it should be explicit: #to_regexp.
Perhaps, yes. It’s not something I’ve ever yearned for personally.
cheers
alex