-4

I want to replace spaces and forward slashes with an underscore, and retain backslashes.

How do I do this?

I have the following regex:

"hello\h /123".gsub(/[\s+\/]/, "_")
#=> "helloh__123"

But it also replaces backslashes in the string.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 4
    The backslash inside a double quoted string literal must be doubled. Or use a single quoted string literal. See https://ideone.com/NqLSk3 – Wiktor Stribiżew Dec 05 '17 at 10:34
  • 3
    Your string does not have any backslashes in it. – Ray Toal Dec 05 '17 at 10:34
  • If I put it in a variable it is coming as a='hello\c /123'.gsub(/\s+|\//, "_") => "hello\\c__123" . But puts gives correct output. How to get it in variable? – explorer Dec 05 '17 at 10:43
  • 1
    @explorer `"hello\h /123"` is not the same as `'hello\h /123'` – Stefan Pochmann Dec 05 '17 at 10:46
  • 1
    `\h` is not an escape sequence. Therefore, `"\h"` is equivalent to `"h"`. From the [documentation](http://ruby-doc.org/core-2.4.2/doc/syntax/literals_rdoc.html#label-Strings): _"Any other character following a backslash is interpreted as the character itself."_ – Stefan Dec 05 '17 at 14:20

1 Answers1

0

So, if you just want to convert space and slash with underscore, you might prefer:

"hello\h /123".tr('/ ','__') # 2nd arg is two underscores
#=> "helloh__123"

(But I agree with the comments on the question so far.)