kmancusi
kmancusi

Reputation: 571

How do I read a file and escape the characters?

I have a file that contains an array of strings like this:

["1234","4567","8899"]

I am opening the file like this:

File.open("./tmp/foo/foo_bar", "r") { |file| file.read }

but it comes back with quotations and "\" like this:

"[\"1234\",\"4567\",\"8899\"]"

How do I have the extra "" and "\" removed?

Upvotes: 0

Views: 67

Answers (1)

m. simon borg
m. simon borg

Reputation: 2575

If you're trying to de-serialize the file and turn the contents into a usable Ruby object, then in this case you can use the JSON library

require 'json'

contents = File.open("./tmp/foo/foo_bar", "r") { |file| file.read } # => "[\"1234\",\"4567\",\"8899\"]"
result = JSON.parse(contents) # => ["1234", "4567", "8899"]
result.is_a?(Array) # => true

Upvotes: 2

Related Questions