Skip to content

Instantly share code, notes, and snippets.

@coffeencoke
Created December 31, 2013 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coffeencoke/8201402 to your computer and use it in GitHub Desktop.
Save coffeencoke/8201402 to your computer and use it in GitHub Desktop.
Why does this happen?
"'this has quotes'".gsub("'", "\\'") # => "this has quotes'this has quotes"
@coffeencoke
Copy link
Author

Why does this not produce: "'this has quotes'"
?

@ggoodale
Copy link

ggoodale commented Mar 5, 2014

Simple answer: because you have one too many backslashes.

Longer answer: Because ' in gsub means "the first part of the match."

@coffeencoke
Copy link
Author

@ggoodale how can I have it result in "'this has quotes'" ?

@ggoodale
Copy link

ggoodale commented Mar 5, 2014

Right, missed that you wanted the backslashes. :) For that, you can use %q:

"'this has quotes'".gsub("'", %q(\\\'))

note that if you're testing this in irb, you'll see double backslashes; stick puts in front to verify that you're getting the right output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment