简体   繁体   中英

Backslash in string returns two backslash

I entered this access token value

864876322670016\%7C4e1d481ecad9eb45b9386745.1-1026038548\%7CshuA8v7lgo7-hRr2AjbUBd3shek

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

864876322670016\\\%7C4e1d481ecad9eb45b9386745.1-1026038548\\\%7CshuA8v7lgo7-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?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM