Use single quote in string validation
I have the following program:
args = ["a", "b"]
cmd_args = args.map{|x| x.inspect}
str = cmd_args.join(' ')
puts str
Output:
"a" "b"
I expect the result to look like this (the substring is quoted with '
instead of "
):
'a' 'b'
I don't want to do gsub
after the string inspect
because on my real system a substring might contain "
. For example:
args = ['a"c', "b"]
cmd_args = args.map{|x| x.inspect.gsub('"', '\'')}
str = cmd_args.join(' ')
puts str
will output:
'a\'c' 'b'
"
between a and c is erroneously replaced. My expected output:
'a"c' 'b'
How can I do string validation for quoting strings using '
instead "
?
source to share
You cannot force the String#inspect
use of a single quote without rewriting or rewriting.
Instead, x.inspect
you can replace "'#{x}'"
, but then you will need to make sure that you avoid any characters '
that appear in x
.
Here it works:
args = ["a", "b"]
cmd_args = args.map{|x| "'#{x}'" }
str = cmd_args.join(' ')
puts str
Output:
'a' 'b'
source to share