-1

Does anyone know how to provide a single backslash as the replacement value in Ruby's gsub method? I thought using double backslashes for the replacement value would result in a single backslash but it results in two backslashes.

Example: "a\b".gsub("\", "\\")

Result: a\\b

I also get the same result using a block:

Example: "a\b".gsub("\"){"\\"}

Result: a\\b

Obviously I can't use a single backslash for the replacement value since that would just serve to escape the quote that follows it. I've also tried using single (as opposed to double) quotes around the replacement value but still get two backslashes in the result.

EDIT: Thanks to the commenters I now realize my confusion was with how the Rails console reports the result of the operation (i.e. a\\b). Although the strings 'a\b' and 'a\\b' appear to be different, they both have the same length:

'a\b'.length (3)

'a\\b'.length (3)

ddb
  • 38
  • 6
  • 1
    Using single quotes does actually work, but the single backslash is represented as "\\". `puts` the resulting string, or verify the size of the string - it's 3. – steenslag May 31 '21 at 17:58
  • ...and note that `"a\b".gsub("\", "\\").each_char.map(&:ord) #=> [97, 92, 98]`. – Cary Swoveland May 31 '21 at 18:13
  • Does this answer your question? [Ruby replace double backslash with single backslash](https://stackoverflow.com/questions/12285747/ruby-replace-double-backslash-with-single-backslash) – Wiktor Stribiżew May 31 '21 at 18:13

1 Answers1

0

You can represent a single backslash by either "\\" or '\\'. Try this in irb, where

 "\\".size

correctly outputs 1, showing that you indeed have only one character in this string, not 2 as you think. You can also do a

 puts "\\" 

Similarily, your example

puts("a\b".gsub("\", "\\"))

correctly prints

a\b
user1934428
  • 19,864
  • 7
  • 42
  • 87