Hello --

On Thu, 16 May 2002, Nikodemus Siivola wrote:

> On Thu, 16 May 2002, William Djaja Tjokroaminata wrote:
>
> > the special case such as above (we know how reg was created from str), is
> > there an easy way to convert reg to str?
>
> Untested && unsporting && wasteful code follows, taking lead from Nobu's
> suggestion to save the string -- let the class do it for you...
>
> class Regexp
>   alias old_escape escape
>   def Regexp.escape(string)
>     escaped = old_escape(string)
>     @@unescape = {} unless defined?(@@unescape)
>     @@unescape[escaped]=string
>     return escaped
>   end
>   def Regexp.unescape(regexp)
>     @@unescape[regexp] || raise
>   end
> end

Too much work :-)  Here's a simpler, Nobu-derived way:

  class << Regexp
    def unescape(re)
      re.source.sub(/\A\\A/, '').sub(/\\z\z/, '').gsub(/\\(.)/, '\1')
    end
  end

I think this is better, design-wise, than storing them in a
(class-wide) hash, because the hash mixes per-object intelligence and
class functionality.  (Mind you, I haven't really thought through the
nuances of any of this... just thinking out loud.)


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav