Forum: Ruby Re: String interpretation

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jamal M. (Guest)
on 2006-04-25 23:48
(Received via mailing list)
The eval technique works for now--thanks!  Is there also a way I can
reverse the conversion, i.e., getting a string with standard (not
RegExp) tokens from a string variable that has the actual characters,
themselves?

Jamal
unknown (Guest)
on 2006-04-26 00:38
(Received via mailing list)
On Wed, 26 Apr 2006, Jamal M. wrote:

> The eval technique works for now--thanks!  Is there also a way I can
> reverse the conversion, i.e., getting a string with standard (not
> RegExp) tokens from a string variable that has the actual characters,
> themselves?

with each and every feature creep you'll be wanting something like this:


   harp:~ > cat a.rb
   class SearchExpression < ::String
     INTERPOLATE = {
       '\n' => "\n",
       '\t' => "\t",
       '\r' => "\r",
       '\f' => "\f",
     }
     def initialize *a, &b
       super and interpolate!
     end
     def interpolate!
       INTERPOLATE.each do |k,v|
         gsub! Regexp::new(Regexp::escape(k)), v
       end
     end
     def uninterpolate!
       INTERPOLATE.invert.each do |k,v|
         gsub! Regexp::new(Regexp::escape(k)), v
       end
     end
   end

   s = SearchExpression::new 'foo\tbar\n'
   p s
   puts s

   s.uninterpolate!
   p s
   puts s



   harp:~ > ruby a.rb
   "foo\tbar\n"
   foo     bar
   "foo\\tbar\\n"
   foo\tbar\n


cheers.

-a
This topic is locked and can not be replied to.