2

I want to read data.txt file and output the same as string2, but when I read from the file Ruby prints the backslashes, why is that so and how can I avoid it?

data.txt contains

\",\"foo\":{\"id\":1111,\"name\":\"Bar\",

file = File.open("data.txt", "r")
string1 = file.read

puts "string1: #{string1}"

string2 = "\",\"foo\":{\"id\":1111,\"name\":\"Bar\","
puts "string2: #{string2}"

Output

$ ruby test.rb
\",\"role\":{\"id\":1111,\"name\":\"Mobile\",
","role":{"id":1111,"name":"Mobile",

My goal is to read data.txt and output ","role":{"id":1111,"name":"Mobile",

3
  • Why do you pass the binary option to the open call? Commented May 8, 2014 at 23:59
  • removed the open binary option but seems to be the common way when reading a File to String Commented May 9, 2014 at 0:09
  • @AndréRicardo In that example they're opening a gzip file, which is a binary file format. If you're opening a text file, the binary option is unnecesary. Commented May 9, 2014 at 15:53

2 Answers 2

0

I the data read from the file the backslashes are part of the data. in your string2 the backslashes are escape characters.

There are pr1obably better ways to to this but , you could probably just use gsub to get ride of the backslashes. try this and see if it does what you want

string1.gsub(/[\\\"]/,"")

if you just want to remove the /'s

string1.gsub(/\\/,"") should work also
Sign up to request clarification or add additional context in comments.

2 Comments

I tested this, but had to change it to .gsub(/[\]/,"") for the expected results
oops, sorry I missed that you wanted to keep the "'s
0

When you read the text file the escape characters are actually there in the file, so they are read and added to your string.

When you generate a string in your code the escape characters are interpreted. So \" is replaced with the character " and placed in your variable.

So there is no need to escape the special characters in your input file.

3 Comments

If you want to have an escaped data file and turn it into an unescaped string you could use this call. (It's not pretty) puts "string1: #{eval("puts \"" + @string1 + "\"")}"
That solution for unescaping the string relies on the string in your file being escaped properly in the first place. If it isn't, you'll either get an error, or arbitrary Ruby code could be executed in the context of your application.
Yes. But just arbitrarily removing all the back slashes won't work well for other cases such as an escaped backslash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.