1

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
Patryk
  • 22,602
  • 44
  • 128
  • 244

1 Answers1

2

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

Community
  • 1
  • 1
ihaztehcodez
  • 2,123
  • 15
  • 29