1

I'm using \.br\ as delimiter:

[10, 20, 30].join('\.br\\')

expected result:

"10\.br\20\.br\30"

what is actually returned:

"10\\.br\\20\\.br\\30"

I added escape for the backslash, how could I get the expected result?

user513951
  • 12,445
  • 7
  • 65
  • 82
sean an
  • 127
  • 1
  • 2
  • 12

1 Answers1

5

I think you'll find that the backslashes are not in fact doubled in the string.
To check, instead of printing it using p (which uses String#inspect) just print it using puts.

When the string is inspected it uses double-quotes, and tries to produce a version of the string that you can copy and paste in to Ruby to get the same string - so it needs to double up the backslash characters.

Stefan
  • 109,145
  • 14
  • 143
  • 218
cliffordheath
  • 2,536
  • 15
  • 16
  • i still don't understand. if I use puts, it's good. how exactly could i solve my problem? – sean an Dec 10 '15 at 02:20
  • 1
    @seanan - The point is that you don't have a problem. Your string is exactly how you would expect it, it is irb that displays it in that weird way - as soon as you try to use that string in the application you will see it is normal. – BroiSatse Dec 10 '15 at 02:21
  • 2
    You don't have a problem. The backslashes are not doubled in your string. They're doubled in the printed output which is generated for your string. Print the number of characters instead, to verify that. – cliffordheath Dec 10 '15 at 02:22
  • thanks. is this a ruby thing, or there's some common pattern here? – sean an Dec 10 '15 at 02:36
  • @seanan it's an [irb](http://ruby-doc.org/stdlib-2.2.3/libdoc/irb/rdoc/IRB.html) thing - irb uses `inspect` for output and therefore escapes strings. – Stefan Dec 10 '15 at 09:38