Substitute ' with \' in double-quoted string - ruby

The task is simple - I have a string like "I don't know" and I want substitute ' with \' (I know that I don't have to escape single quotes). How can I do it?

Try using the block form, it should work in all versions of Ruby:
s.gsub(/'/) {"\\'"}
# => "I don\\'t know"
[Edit]
The reason is that the gsub method has special handling for backslash sequences in the replacement string which correspond to the special match variables. So you can use $' (and $1, etc.) directly in the substituted string by using the form \\' (and \\1, etc.) instead.
The block form of gsub doesn't have this behavior, so that's the workaround when you're trying to sub in a string that looks like a special backslash sequence.

Related

Having a single quote inside a single quoted string

My question targets Zsh, but from what I tried, it seems to apply to POSIX shell and bash as well:
I want to write a string containing literal $ characters (no interpolation intended) and single quotes. Since the chapter on QUOTING in the Zsh man page says about single-quoted strings:
A literal ' character can be included in the string by using the \' escape.
I tried something like this (in an interactive zsh, before doing it in a script):
echo 'a$b\'c'
I expected that this would print a$b'c, but zsh tells me that I have an unclosed quote.
I am aware that I can use as a workaround
echo 'a$'"b'C"
but I still would like to know, why my original attempt failed.
The problem was my interpretation of the man-page, and I must blame myself that I have left out of my citation of the page one part which I thought is unimportant, but actually is relevant for this case. Here again the full sentence of the man page:
A string enclosed between '$'' and ''' is processed the same way as the
string arguments of the print builtin, and the resulting string is
considered to be entirely quoted. A literal ''' character can be
included in the string by using the '\'' escape.
Since Zsh has two ways to write a single-quoted String (one where the quotation, like in bash, starts with ' and one where it starts with $'), I understood the between ... and part that it meant "in $' and in ' -quoted strings, the \' escape works.
This interpretation is incorrect. What the man page means is that a quoted string which starts with $' and ends with ', can use that escape.
Hence my example can written as
echo $'a$b\'c'

How come you can't gsub this string in Ruby?

These \\n are showing up in my strings even though it should only be \n.
But if I do this :
"\n".gsub('\\n','\b')
It returns :
"\n"
Ideally, I'm trying to find a regex that could rewrite this string :
"R3pQvDqmz/EQ7zho2mhIeE6UB4dLa6GUH7173VEMdGCcdsRm5pernkqCgbnj\\nZjTX\\n"
To not display two backslashes, but just one like this :
"R3pQvDqmz/EQ7zho2mhIeE6UB4dLa6GUH7173VEMdGCcdsRm5pernkqCgbnj\nZjTX\n"
But any of the regex I do will not work. I can gsub out the \n and put something like X there, but if I put a \ in it, then Ruby escapes it with an additional \ which consequentially destroys my encryption module as it needs to be specific.
Any ideas?
You are falling into the trap of a different meaning of escapes when used in strings with double quotes vs single quotes. Double-quoted strings allow escape characters to be used. Thus, here "\n" actually is a one-character string containing a single line feed. Compare that to '\n' which is a two-character string containing a literal backslash followed by a character n.
This explains, whey your gsub doesn't match. If you use the following code, it should work:
"\\n".gsub('\n','\b')
For your actual issue, you can use this
string = "R3pQvDqmz/EQ7zho2mhIeE6UB4dLa6GUH7173VEMdGCcdsRm5pernkqCgbnj\\nZjTX\\n"
new_string = string.gsub("\\n", "\n")

Ruby string with quotes for shell command args?

Hi I need to create string like this:
drawtext="fontfile=/Users/stpn/Documents/Video_Experiments/fonts/Trebuchet_MS.ttf:text='content':fontsize=100:fontcolor=red:y=h/2"
I want to do something like
str = Q%[drawtext="fontfile=/Users/stpn/Documents/Video_Experiments/fonts/Trebuchet_MS.ttf:text='content':fontsize=100:fontcolor=red:y=h/2"]
I am getting this:
=> "drawtext=\"fontfile=/Users/stpn/Documents/Video_Experiments/fonts/Trebuchet_MS.ttf:text='content':fontsize=100:fontcolor=red:y=h/2\""
The escape characters after equals sign in drawtext=" is what I want to get rid of.. How to achieve that?
The string is to be used in a command line args.
Like many languages, Ruby needs a way of delimiting a quoted quote, and the enclosing quotes.
What you're seeing is the escape character which is a way of saying literal quote instead of syntactic quote:
foo = 'test="test"'
# => "test=\"test\""
The escape character is only there because double-quotes are used by default when inspecting a string. It's stored internally as a single character, of course. You may also see these in other circumstances such as a CR+LF delimited file line:
"example_line\r\n"
The \r and \n here correspond with carriage-return and line-feed characters. There's several of these characters defined in ANSI C that have carried over into many languages including Ruby and JavaScript.
When you output a string those escape characters are not displayed:
puts foo
test="test"

How to make Ruby ignore backslash in strings?

Is there some way in Ruby that I can avoid having to put double-backslash in Ruby strings (like what can be done in C#):
For example, in C# was can prefix a string with # and then the backslash in the string does not need to be escaped:
#"C:\Windows, C:\ABC"
Without # we would need to escape the backslash:
"C:\\Windows, C:\\ABC"
Is there something similar in Ruby?
Use single quotes
my_string = 'C:\Windows'
See more in the Strings section here
You can also use %q and backslashes will be automatically escaped for you:
%q{C:\Windows} => "C:\\Windows"

Watir magic escape sequence?

I am currently using Watir with Firefox and it seems that when I try to set a field with the following text:
##$QWER7890uiop
The command I am using is the following:
text_field(:name, "password").value=("!##$QWER7890uiop)
I've also tried this:
text_field(:name, "password").set "!##$QWER7890uiop)
Only the first 2 characters get entered. Is there something I can do to by pass this feature?
You need to escape the string using single quotes '.
text_field(:name, "password").value='"!##$QWER7890uiop'
Many characters are substituted inside double quotes.
Escape sequences like \n, \t, \s, etc are replaced by their equivalent character(s). See here for full list.
#{} where anything the braces is interpreted as a ruby expression.
#$something where $something is interpreted as a ruby global variable. That's the problem with your quote above, beside not being terminated.
%s is interpreted as an ERB template expression (it is interpolated).
For instance:
puts "%s hours later" % 'Five'
results in
"Five hours later".

Resources