# Reprocess Escape Sequences

**URL:** <https://www.ruby-forum.com/t/reprocess-escape-sequences/187405>\
**Category:** Ruby\
**Created:** [April 22, 2010, 5:46pm UTC](https://www.ruby-forum.com/t/reprocess-escape-sequences/187405 "2010-04-22T17:46:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![nmadura](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/53a042/32.png) [@nmadura](https://www.ruby-forum.com/u/nmadura)\
**Post date:** [April 22, 2010, 5:46pm UTC](https://www.ruby-forum.com/t/reprocess-escape-sequences/187405/1 "2010-04-22T17:46:00Z")

</div>

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

> > str = ‘some \n\r string \t with \r escape \n sequences’  
> > =\> “some \n\r string \t with \r escape \n sequences”
> 
> > eval “puts str”  
> > some \n\r string \t with \r escape \n sequences  
> > =\> nil
> 
> > puts “%s” % str  
> > some \n\r string \t with \r escape \n sequences  
> > =\> nil

I recognize that I can simply do a gsub:

> > puts str.gsub(/\n/, “\n”)  
> > 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?

---

<div class="post-metadata">

**Author:** ![nmadura](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/53a042/32.png) [@nmadura](https://www.ruby-forum.com/u/nmadura)\
**Post date:** [April 23, 2010, 12:56pm UTC](https://www.ruby-forum.com/t/reprocess-escape-sequences/187405/2 "2010-04-23T12:56:46Z")

</div>

2010/4/22 Nathaniel M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

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

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

irb(main):004:0\> str = ‘some \n\r string \t with \r escape \n sequences’  
=\> “some \n\r string \t with \r escape \n sequences”  
irb(main):005:0\> puts eval(‘"’+str+‘"’)  
some  
escape with  
sequences  
=\> nil  
irb(main):006:0\>

> =\> 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 = {‘n’=\>“\n”,‘t’=\>“\t”,‘r’=\>“\r”}  
=\> {“n”=\>“\n”, “t”=\>“\t”, “r”=\>“\r”}  
irb(main):009:0\> str.gsub(/\(.)/){|m| PAT[$1]}  
=\> “some \n\r string \t with \r escape \n sequences”

Kind regards

robert
