Do ternary evaluations need to be parameterized? - ruby

It seems that if I put code in my ternary evaluation it fails, but placing true or false it works.
Here is my code:
>test = [nil]
=> [nil]
>test.any? ? puts "AAA" : puts "BBB"
SyntaxError: (irb):16: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
test.any? ? puts "AAA" : puts "BBB"
^
(irb):16: syntax error, unexpected ':', expecting $end
test.any? ? puts "AAA" : puts "BBB"
>test.any? ? true : false
=> false
>test << 1
=> [nil, 1]
>test.any? ? true : false
=> true
>test.any? ? puts "AAA" : puts "BBB"
SyntaxError: (irb):14: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
test.any? ? puts "AAA" : puts "BBB"
^
(irb):14: syntax error, unexpected ':', expecting $end
test.any? ? puts "AAA" : puts "BBB"
^

You need parentheses.
>> test.any? ? puts("AAA") : puts("BBB")
BBB
=> nil
You should avoid parentheseless call in inline functions.

Related

use Chef file.insert_line_if_no_match method for CIDR address

I am trying to use file.insert_line_if_no_match for CIDR address:
attributes/default.rb:
default["chefclustercidr"]["ip"] = "a.b.c.d/24"
recipe/default.rb
ruby_block "chef-backend.rb" do
block do
file = Chef::Util::FileEdit.new("/etc/chef-backend/chef-backend.rb")
file.insert_line_if_no_match("/publish_address/" , "publish_address i#{node['chefclusterbe1']['ip']}")
file.insert_line_if_no_match("/postgresql/" , "postgresql.md5_auth_cidr_addresses = ["samehost", "samenet", "#{node['chefclustercidr']['ip']}/24"]")
file.write_file
end
end
but getting ruby syntax error
$ruby -c default.rb
default.rb:95: syntax error, unexpected tIDENTIFIER, expecting ')'
th_cidr_addresses = ["samehost", "samenet","#{node['chefclus
^
default.rb:95: syntax error, unexpected tIDENTIFIER, expecting keyword_end
resses = ["samehost", "samenet","#{node['chefclustercidr']['
^
default.rb:99: syntax error, unexpected keyword_end, expecting end-of-input
FileEdit is an internal class and using it from recipe code is NOT SUPPORTED. Do not use it. Period.
That said, the problem is you have unescaped double quotes in your string.
Instead of insert_line_if_no_match you can deal with it another way, using bash and grep. I have added the way to another question you can have a look here
here is the bash resource i usually use to append to files only if there is no match:
bash 'append line(s) to file if it doesnt exist' do
user 'user'
code <<-EOS
cat >>/home/file <<EOL
*.* ##172.167.189.67:514
EOL
EOS
not_if "grep -q 172.167.189.67 /home/file"
end
you may need to run cookstyle on that ^

Escaping double quotes in Ruby's gsub

I'm trying to minify some inline JSON as part of my HTML minifier. How do I make this:
> {"#context": "http://schema.org", "#type": "WebSite"} <
Into this:
>{ "#context": "http://schema.org", "#type": "WebSite" }<
I've tried gsub[/\", \s+\"/, ", "], gsub[/"\"}"/, "\" }"] and gsub[/"\"}"/, "\" }"] but that errors out.
syntax error, unexpected [, expecting ']' (SyntaxError)
[/"\"}"/, "\" }"]
^
syntax error, unexpected ',', expecting keyword_end
syntax error, unexpected ',', expecting keyword_end
syntax error, unexpected ']', expecting keyword_end
UPDATE
I've now also tried these but to no good:
[/>\s+{/, ">{ "] # > { => >{
[/}\s+>/, " }<"] # } < => }<
[%r/{"/, '{ %r/"'] # {" => { "
[%r/"}/, '%r/" }'] # "} => " }
[%r/",\s+/, ", "] # , " => , "
Resulting in:
syntax error, unexpected [, expecting ']' (SyntaxError)
[/}\s+>/, " }<"] # } < => }<
^
I would suggest a different approach:
require JSON
str = '{"#context": "http://schema.org", "#type": "WebSite"}'
new_str = JSON.parse(str).to_json
puts new_str
> {"#context":"http://schema.org","#type":"WebSite"}
Use a %r Regexp literal to escape all characters but one :
a = '{"#context": "http://schema.org", "#type": "WebSite"}'
a.gsub(%r/{"/, '{ "').gsub(%r/"}/, '" }').gsub(/\s+/, ' ')
#=> { "#context": "http://schema.org", "#type": "WebSite" }
using %r{ ... } escapes all characters but { and },same goes for /, (, etc ...
credit : Escaping '“' with regular double quotes using Ruby regex
It will escapes double quotes
gsub(/("|")/, 34.chr)

How to run 2 commands only if first succeeded in ruby?

I would like to run 2 commands in ruby but only if the first one succeeds.
In bash I would use && operator. I have tried this one and and keyword but && has thrown an error and and operator didn't works as expected.
The example I want to use it for:
#!/usr/bin/ruby
#
puts "asd" and puts "xxx"
executed as:
$ ./asd.rb
asd
The keyword and has lower precedence than &&. Both use short-circuit evaluation.
First, note that puts always returns nil. In ruby, nil is falsey.
2.2.0 :002 > puts "asdf"
asdf
=> nil
Now we try your example:
2.2.0 :002 > puts "asd" and puts "xxx"
asd
=> nil
This is the same as:
puts("asd") && puts("xxx")
asd
=> nil
In both cases puts "asd" and puts("asd") return nil so puts "xxx" and puts("xxx") are never evaulated because nil is falsey and there is short-circuit evaulation being used.
You also tried puts "asd" && puts "xxx", but this is a syntax error because of the higher precendence of the && operator.
puts "asd" && puts "xxx"
SyntaxError: (irb):3: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
puts "asd" && puts "xxx"
^
That's because puts "asd" && puts "xxx" is the same as puts("asd" && puts) "xxx".
2.2.0 :012 > puts("asd" && puts) "xxx"
SyntaxError: (irb):12: syntax error, unexpected tSTRING_BEG, expecting end-of-input
puts("asd" && puts) "xxx"
^
See also: this related post

Ruby unexpected $end, expecting keyword_end

I get the following error from my code.
ruby -w search.rub search.rub:19: warning: mismatched indentations at 'end' with 'case' at 12 search.rub:62: syntax error, unexpected $end, expecting keyword_end
I have a feeling that it has something to do with all the ends.
#!/usr/bin/ruby
num_line = 0
NumDiccionario = 1
def checkPassword (pass)
print pass, "\t"
system("bitcoind", "walletpassphrase", pass, "20")
case $?.exitstatus
when 0
puts "You found it!#{pass}"
File.open('password.txt', 'w') do |file|
file.puts phrase + "\n"
end
exit 0
end
str_num_line = "0"
File.open('lastLine.txt', 'r') do |file2|
str_num_line = file2.gets
end
if (str_num_line.to_i > 0 )
print "Last searching stopped at line " + str_num_line + "\n"
STDOUT.flush
print "Continue from here? y/n:"
resp = gets.chomp
if (resp == "y")
num_line =str_num_line.to_i
end
end
def checkPassword (pass)
print pass, "\t"
system("bitcoind", "walletpassphrase", pass, "20")
case $?.exitstatus
when 0
puts "You found it!#{pass}"
File.open('password.txt', 'w') do |file|
file.puts phrase + "\n"
end
end
exit 0
end

What's wrong with my array initialization in ruby?

Why is this a syntax error in ruby?
#!/usr/bin/ruby
servers = [
"xyz1-3-l"
, "xyz1-2-l"
, "dws-zxy-l"
, "abcl"
]
hostname_input = ARGV[0]
hostname = hostname_input.gsub( /.example.com/, "" )
servers.each do |server|
if hostname == server then
puts "that's the one"
break
end
end
... when I execute this script I get this output ...
$ ./test.rb abc1
./test.rb:5: syntax error, unexpected ',', expecting ']'
, "xyz1-2-l"
^
./test.rb:6: syntax error, unexpected ',', expecting $end
, "dws-zxy-l"
^
... if I simply put everything on the same line its ok ...
$ cat test.rb
#!/usr/bin/ruby
servers = [ "xyz1-3-l" , "xyz1-2-l" , "dws-zxy-l" , "abcl" ]
hostname_input = ARGV[0]
hostname = hostname_input.gsub( /.example.com/, "" )
servers.each do |server|
if hostname == server then
puts "that's the one"
break
end
end
$ ./test.rb dws-zxy-l
that's the one
Look ma, no commas (or quotes):
servers = %W[
xyz1-3-l
xyz1-2-l
dws-zxy-l
abcl
]
# => ["xyz1-3-l", "xyz1-2-l", "dws-zxy-l", "abcl"]
Newlines are significant in Ruby. You need to put the comma at the end of the line or use a backslash before your newline to indicate that the line is continuing (of course, in that case, what's the point in moving the comma to the next line?).

Resources