String interpretation

First, I'm curious why a string delimited with apostrophe characters is
not interpreted completely literally. Why does the language make an
exception for the backslash character so that it needs to be doubled
there as well?

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.

If I save the user's find string to a variable (using WxRuby), and then
search for it using the index method, tokens such as \n are interpreted
literally. I thought that maybe

input = "#{input}"
would translate the characters, but this does not work, and I have not
yet found a way.

Jamal

Hi --

···

On Wed, 26 Apr 2006, Jamal Mazrui wrote:

First, I'm curious why a string delimited with apostrophe characters is
not interpreted completely literally. Why does the language make an
exception for the backslash character so that it needs to be doubled
there as well?

Because you need the backslash to do:

   '\''

so then you need a way to indicate the backslash itself :slight_smile:

David

--
David A. Black (dblack@wobblini.net)
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)

"Ruby for Rails" PDF now on sale! Ruby for Rails
Paper version coming in early May!

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

···

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.

--
be kind whenever possible... it is always possible.
- h.h. the 14th dali lama