steamboy
steamboy

Reputation: 1162

Backslash in string returns two backslash

I entered this access token value

864876322670016\u00257C4e1d481ecad9eb45b9386745.1-1026038548\u00257CshuA8v7lgo7-hRr2AjbUBd3shek

on a form but it was returned with double backslash like this

864876322670016\\u00257C4e1d481ecad9eb45b9386745.1-1026038548\\u00257CshuA8v7lgo7-hRr2AjbUBd3shek

I'm passing this value to Facebook GraphAPI and this returns an error.

How can I get return replace the double backslash with a single one? or is there a way for the double backslash to not appear?

Upvotes: 1

Views: 1016

Answers (2)

Casper
Casper

Reputation: 34308

Are you sure it's actually returned with double backslashes? Internally strings with backslashes will look like they have double backslashes because Ruby is escaping them:

> a = 'aaa\bbb\ccc'
=> "aaa\\bbb\\ccc"           # Looks like doubles
> a
=> "aaa\\bbb\\ccc"
> a.inspect
=> "\"aaa\\\\bbb\\\\ccc\""   # Looks even worse
> puts a
aaa\bbb\ccc                  # ...but it isn't

But if they are double backslashes you can do something like this:

> puts aa
aaa\\bbb\\ccc                # String with double backslash
> aa.gsub!("\\\\", "\\")
> puts aa
aaa\bbb\ccc

Upvotes: 6

jefflunt
jefflunt

Reputation: 33954

It's just the way it's being displayed, in escaped form. Your error is likely elsewhere.

This is a common misinterpretation of the output, and a little confusing when you first see it, as Casper has pointed out.

From this question/answer, where the person's issue was essentially the same:

Dang it. I forgot that when the result is displayed in double quotes it shows it escaped.

There's also a short discussion of this perceived issue in this blog post.

Upvotes: 1

Related Questions