How can I print double quotes in ruby - ruby

Am trying to bring output like below in AWS console for Cloudwatch metric filter pattern
[w1,w2,w3,w4=!"*10.1.1.1*"&&w5=!"*10.1.1.2*"&&w5="*admin*"]
for one of my ruby aws sdk script with below function
data_of_ips = ["10.1.1.1", "10.1.1.2"]
def run_me(data_of_ips)
:::
:::
filter_pattern = '[w1,w2,w3,w4!='"*#{data_of_ips[0]*"'&&w4!='"*#{data_of_ips[1]*"',w5="*admin*"]'
but in the aws console output I could see the output like below without " (double quotes) for w4.
[w1,w2,w3,w4=!*10.1.1.1*&&w4=!*10.1.1.2*&&w5="*admin*"]
Please help me out to fix this.

Is this what you expect?
data_of_ips = ["10.1.1.1", "10.1.1.2"]
def run_me(data_of_ips)
"[w1,w2,w3,w4!=\"*#{data_of_ips[0]}*\"&&w4!=\"*#{data_of_ips[1]}*\"&&w5=\"*admin*\"]"
end
puts run_me(data_of_ips)
# => [w1,w2,w3,w4!='"*10.1.1.1*"&&w4!="*10.1.1.2*"&&w5="*admin*"]
If you want to put variable or script inside a string, I suggest you can use double quote with #{} to do that. It's more clear. And the special char like " you can just use \" to write them.

I fixed it this way:
filter_pattern = '[w1,w2,w3,w4!="'"*#{data_of_ips[0]}*"'"&&w4!="'"*#{data_of_ips[1]}*"'"w5="*admin"]'
I used "'" (double-quotes single-quote double-quotes) and got the expected output below:
filter_pattern = '[w1,w2,w3,w4!="*10.1.1.1*"&&w4!="*10.1.1.2*",w5"*admin*"]'

Related

How to add single quotes across a string in ruby?

I am iterating over a config.yml from from which parsing the values in a string form as follows:
machines:
A:
ip: 10.11.12
pass: vass
B:
ip: 10.11.13
pass: grass
The above config.yml is parsed as follows:
machines = YAML.load_file('machine.yml')
var=''
machines[A].each do |letters,hash|
var += "[" + hash['ip'] + "]\n" + hash['pass'] + "\n"
end
The "var" value i am getting as :
"[10.11.12]\nvass\n[10.11.13]\ngrass\n"
but instead like above i dont want double quotes rather single quotes across complete atring as follows:
'[10.11.12]\nvass\n[10.11.13]\ngrass\n'
So, please suggest how can have single quotes across the string.
Generally the puts will print the value of the string without double quotes in the console.
So may be you can use puts var so that double quotes are not getting printed. And now you can wrap your content with single quote using string interpolation.
var += "'#{actual_value}'"

Concat a number's value in a String in Ruby

I am running test with Capybara on Ruby. I got an error for this code
pos = rand languages.size
# advanced_search.adv_language_labels[pos].click
script = "$('label[for*='lang']:eq(" + pos.to_s + ")').click()"
page.execute_script script
How can I get this 'pos' value to the script so that I can run with execute_script command? Thanks.
The string you're generating looks like this:
$('label[for*='lang']:eq(5)').click()
Note there's an internal pair of single quotes that's closing out the label path before you mean to. You need to escape those.
$('label[for*=\'lang\']:eq(5)').click()

regex replace [ with \[

I want to write a regex in Ruby that will add a backslash prior to any open square brackets.
str = "my.name[0].hello.line[2]"
out = str.gsub(/\[/,"\\[")
# desired out = "my.name\[0].hello.line\[2]"
I've tried multiple combinations of backslashes in the substitution string and can't get it to leave a single backslash.
You don't need a regular expression here.
str = "my.name[0].hello.line[2]"
puts str.gsub('[', '\[')
# my.name\[0].hello.line\[2]
I tried your code and it worked correct:
str = "my.name[0].hello.line[2]"
out = str.gsub(/\[/,"\\[")
puts out #my.name\[0].hello.line\[2]
If you replace putswith p you get the inspect-version of the string:
p out #"my.name\\[0].hello.line\\[2]"
Please see the " and the masked \. Maybe you saw this result.
As Daniel already answered: You can also define the string with ' and don't need to mask the values.

Read string as variable RUBY

I am pulling the following string from a CSV file, from cell A1, and storing it as a variable:
#{collector_id}
So, cell A1 reads #{collector_id}, and my code essentially does this:
test = #excel_cell_A1
However, if I then do this:
puts test
I get this:
#{collector_id}
I need #{collector_id} to read as the actual variable collector_id, not the code that I am using to call the variable. Is that possible?
Thanks for the help. I am using ruby 1.9.3.
You can use sub or gsub to replace expected input values:
collector_id = "foo"
test = '#{collector_id}'
test.sub("\#{collector_id}", "#{collector_id}") #=> "foo"
I would avoid the use of eval (or at least sanity check what you are running) to reduce the risk of running arbitrary code you receive from the CSV file.
Try this:
test_to_s = eval("\"#{ test }\"")
puts test_to_s
%q["#{ test }"] will build the string "#{collector_id}" (the double quotes are part of the string, "#{collector_id}".length == 17) which then will be evaluated as ruby code by eval

Escaping single and double quotes in a string in ruby?

How can I escape single and double quotes in a string?
I want to escape single and double quotes together. I know how to pass them separately but don't know how to pass both of them.
e.g: str = "ruby 'on rails" " = ruby 'on rails"
My preferred way is to not worry about escaping and instead use %q, which behaves like a single-quote string (no interpolation or character escaping), or %Q for double quoted string behavior:
str = %q[ruby 'on rails" ] # like single-quoting
str2 = %Q[quoting with #{str}] # like double-quoting: will insert variable
See https://docs.ruby-lang.org/en/trunk/syntax/literals_rdoc.html#label-Strings and search for % strings.
Use backslash to escape characters
str = "ruby \'on rails\" "
Here is a complete list:
From http://learnrubythehardway.org/book/ex10.html
You can use Q strings which allow you to use any delimiter you like:
str = %Q|ruby 'on rails" " = ruby 'on rails|
>> str = "ruby 'on rails\" \" = ruby 'on rails"
=> "ruby 'on rails" " = ruby 'on rails"
I would go with a heredoc if I'm starting to have to worry about escaping. It will take care of it for you:
string = <<MARKER
I don't have to "worry" about escaping!!'"!!
MARKER
MARKER delineates the start/end of the string. start string on the next line after opening the heredoc, then end the string by using the delineator again on it's own line.
This does all the escaping needed and converts to a double quoted string:
string
=> "I don't have to \"worry\" about escaping!!'\"!!\n"
I would use just:
str = %(ruby 'on rails ")
Because just % stands for double quotes(or %Q) and allows interpolation of variables on the string.
Here is an example of how to use %Q[] in a more complex scenario:
%Q[
<meta property="og:title" content="#{#title}" />
<meta property="og:description" content="#{#fullname}'s profile. #{#fullname}'s location, ranking, outcomes, and more." />
].html_safe
One caveat:
Using %Q[] and %q[] for string comparisons is not intuitively safe.
For example, if you load something meant to signify something empty, like "" or '', you need to use the actual escape sequences. For example, let's say qvar equals "" instead of any empty string.
This will evaluate to false
if qvar == "%Q[]"
As will this,
if qvar == %Q[]
While this will evaluate to true
if qvar == "\"\""
I ran into this issue when sending command-line vars from a different stack to my ruby script. Only Gabriel Augusto's answer worked for me.

Resources