# How can I get this backslash-eliminating behavior when reading a file?

**URL:** <https://www.ruby-forum.com/t/how-can-i-get-this-backslash-eliminating-behavior-when-reading-a-file/124627>\
**Category:** Ruby\
**Created:** [December 31, 2007, 7:25am UTC](https://www.ruby-forum.com/t/how-can-i-get-this-backslash-eliminating-behavior-when-reading-a-file/124627 "2007-12-31T07:25:08Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![philthompson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ed8c4c/32.png) [@philthompson](https://www.ruby-forum.com/u/philthompson)\
**Post date:** [December 31, 2007, 7:25am UTC](https://www.ruby-forum.com/t/how-can-i-get-this-backslash-eliminating-behavior-when-reading-a-file/124627/1 "2007-12-31T07:25:08Z")

</div>

I’m trying to write a parser for a file format that allows backslashes  
‘’ at the end of lines. The format I’m trying to parse treats  
backslashes at the end of lines just like the Ruby parser would treat  
them if they occured in a ruby source file.

The double quotes string constructor does what I want it to in this  
case:

irb(main):006:0\> str = “line1   
irb(main):007:0” still more line1   
irb(main):008:0" even more line1"  
=\> “line1 still more line1 even more line1” \<- this is exactly what I  
want

However, if I read a string in from a file, I don’t get what I want:  
$ cat testfile  
line 1   
still on line 1  
even more line 1

irb(main):001:0\> str = File.read(“testfile”)  
=\> “line 1 \\nstill on line 1\\neven more line 1\n”

I’d prefer not to even know about the backslashes or '\n’s, so I’d  
rather have the behavior that the double quotes string constructor  
gives me:  
=\> “line1 still more line1 even more line1”

Is there any way to get this behavior when reading a file into a string?

Phil

---

<div class="post-metadata">

**Author:** ![philthompson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ed8c4c/32.png) [@philthompson](https://www.ruby-forum.com/u/philthompson)\
**Post date:** [December 31, 2007, 7:37am UTC](https://www.ruby-forum.com/t/how-can-i-get-this-backslash-eliminating-behavior-when-reading-a-file/124627/2 "2007-12-31T07:37:23Z")

</div>

On 12/30/07, Phil T. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> =\> “line1 still more line1 even more line1” ← this is exactly what I want
> 
> I’d prefer not to even know about the backslashes or '\n’s, so I’d  
> rather have the behavior that the double quotes string constructor  
> gives me:  
> =\> “line1 still more line1 even more line1”
> 
> Is there any way to get this behavior when reading a file into a string?
> 
> Phil

ah, of course, I could just to this:  
str = File.read(“testfile”).gsub(/\\n/,‘’)

That does what I asked for… now I realize that I probably don’t want  
to do this since the line numbering will be all off when reporting  
errors…

Phil
