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",

André Ricardo
  • 3,051
  • 7
  • 23
  • 32
  • Why do you pass the binary option to the `open` call? – squiguy May 08 '14 at 23:59
  • removed the open binary option but seems to be the common way when [reading a File to String](http://stackoverflow.com/questions/130948/ruby-convert-file-to-string) – André Ricardo May 09 '14 at 00: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. – Ajedi32 May 09 '14 at 15:53

2 Answers2

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.

John C
  • 4,276
  • 2
  • 17
  • 28
  • 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 + "\"")}"` – John C May 09 '14 at 00:28
  • 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. – Ajedi32 May 09 '14 at 16:11
  • Yes. But just arbitrarily removing all the back slashes won't work well for other cases such as an escaped backslash. – John C May 09 '14 at 22:08
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
nPn
  • 16,254
  • 9
  • 35
  • 58