Reprocess Escape Sequences

N

Nathaniel Madura

I am getting a string that has escape sequences in it, and I would like
to print it to the screen after reprocessing the escape sequences. Maybe
I have missed something obvious but I haven't seen anything in the docs
that suggest how to do this. To replicate the behaviour I create a
string in irb like so:

$ irbsome \n\r string \t with \r escape \n sequences
=> nilsome \n\r string \t with \r escape \n sequences
=> nil

I recognize that I can simply do a gsub:
some
\r string \t with \r escape
sequences
=> nil

but that would mean I would have to pattern match all sequences, and it
seems like there should be a better way

Any suggestions?
 
R

Robert Klemme

2010/4/22 Nathaniel Madura said:
I am getting a string that has escape sequences in it, and I would like
to print it to the screen after reprocessing the escape sequences. Maybe
I have missed something obvious but I haven't seen anything in the docs
that suggest how to do this. To replicate the behaviour I create a
string in irb like so:

$ irb
some \n\r string \t with \r escape \n sequences
=3D> nil

If you use eval you rather need to do something like this

irb(main):004:0> str =3D 'some \n\r string \t with \r escape \n sequences'
=3D> "some \\n\\r string \\t with \\r escape \\n sequences"
irb(main):005:0> puts eval('"'+str+'"')
some
escape with
sequences
=3D> nil
irb(main):006:0>

some \n\r string \t with \r escape \n sequences
=3D> nil

I recognize that I can simply do a gsub:

some
\r string \t with \r escape
=A0sequences
=3D> nil

but that would mean I would have to pattern match all sequences, and it
seems like there should be a better way

Actually doing a replacement would probably be my preferred way
because of the security implications of eval.

You can do it in one go

irb(main):008:0> PAT =3D {'n'=3D>"\n",'t'=3D>"\t",'r'=3D>"\r"}
=3D> {"n"=3D>"\n", "t"=3D>"\t", "r"=3D>"\r"}
irb(main):009:0> str.gsub(/\\(.)/){|m| PAT[$1]}
=3D> "some \n\r string \t with \r escape \n sequences"

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top