whydealme
whydealme

Reputation:

How to add a single backslash character to a string in Ruby?

I want to insert backslash before apostrophe in "children's world" string. Is there a easy way to do it?

irb(main):035:0> s = "children's world"
=> "children's world"
irb(main):036:0> s.gsub('\'', '\\\'')
=> "childrens worlds world"

Upvotes: 13

Views: 9912

Answers (3)

Jordan Brough
Jordan Brough

Reputation: 7195

Answer

You need some extra backslashes:

>> puts "children's world".gsub("'", '\\\\\'')
children\'s world

or slightly more concisely (since you don't need to escape the ' in a double-quoted string):

>> puts "children's world".gsub("'", "\\\\'")
children\'s world

or even more concisely:

>> puts "children's world".gsub("'") { "\\'" }
children\'s world

Explanation

Your '\\\'' generates \' as a string:

>> puts '\\\''
\'

and \' is a special replacement pattern in Ruby. From ruby-doc.org:

you may refer to some special match variables using these combinations ... \' corresponds to $', which contains string after match

So the \' that gsub sees in the second argument is being interpreted as a special pattern (everything in the original string after the match) instead of as a literal \'.

So what you want gsub to see is actually \\', which can be produced by '\\\\\'' or "\\\\'".

Or, if you use the block form of gsub (gsub("xxx") { "yyy" }) then Ruby takes the replacement string "yyy" literally without trying to apply replacement patterns.

Note: If you have to create a replacement string with a lot of \s you could take advantage of the fact that when you use /.../ (or %r{...}) you don't have to double-escape the backslashes:

>> puts "children's world".gsub("'", /\\'/.source)
children\'s world

Or you could use a single-quoted heredoc: (using <<'STR' instead of just <<STR)

>> puts "children's world".gsub("'", <<'STR'.strip)
  \\'
STR
children\'s world

Upvotes: 15

Magnar
Magnar

Reputation: 28830

>> puts s.gsub("'", "\\\\'")
children\'s world

Upvotes: 5

Chuck
Chuck

Reputation: 237110

Your problem is that the string "\'" is meaningful to gsub in a replacement string. In order to make it work the way you want, you have to use the block form.

s.gsub("'") {"\\'"}

Upvotes: 1

Related Questions