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
···
-----Original Message-----
From: ara.t.howard@noaa.gov [mailto:ara.t.howard@noaa.gov]
Sent: Tuesday, April 25, 2006 2:28 PM
To: ruby-talk ML
Subject: Re: String interpretation
On Wed, 26 Apr 2006, Jamal Mazrui wrote:
Second, how do I ensure that tokens are translated in a string
variable?
I am developing a program with a search feature. I want the user to
be
able to indicate carriage return, line feed, tab, and form feed
characters using the standard tokens of \r, \n, \t, and \f. I do not
want them to have to specify a true regular expression, however, since
other characters such as a period would then need to be escaped and I
want to minimize user knowledge requirements.
irb(main):007:0> s = 'foo\tbar\n'
=> "foo\\tbar\\n"
irb(main):008:0> s = eval "%Q(#{ s })"
=> "foo\tbar\n"
irb(main):009:0> puts s
foo bar
=> nil
but i would advise against this. instead, just make a little parser
class:
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
end
s = SearchExpression::new 'foo\tbar\n'
p s
puts s
harp:~ > ruby a.rb
"foo\tbar\n"
foo bar
easy cheasy.
-a
--
be kind whenever possible... it is always possible.
- h.h. the 14th dali lama