如何仅在 ruby 中首次成功时才 运行 2 个命令?

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

我想 运行 ruby 中的 2 个命令,但前提是第一个命令成功。

在 bash 中我会使用 && 运算符。我试过这个和 and 关键字但是 && 抛出了一个错误并且 and 运算符没有按预期工作。

我想用它的例子:

#!/usr/bin/ruby
#
puts "asd" and puts "xxx"

执行为:

$ ./asd.rb
asd

关键字 and 的优先级低于 &&。两者都使用 short-circuit evaluation.

首先,请注意 puts 总是 returns nil。在 ruby 中,nil 是假的。

2.2.0 :002 > puts "asdf"
asdf
 => nil

现在我们试试你的例子:

2.2.0 :002 > puts "asd" and puts "xxx"
asd
 => nil

这等同于:

puts("asd") && puts("xxx")
asd
 => nil

在这两种情况下 puts "asd"puts("asd") return nil 所以 puts "xxx"puts("xxx") 永远不会被评估,因为 nil是错误的,并且正在使用短路评估。

您也尝试了 puts "asd" && puts "xxx",但这是一个语法错误,因为 && 运算符的优先级更高。

puts "asd" &&  puts "xxx"
SyntaxError: (irb):3: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
puts "asd" &&  puts "xxx"
                     ^

那是因为 puts "asd" && puts "xxx"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"
                     ^

另请参阅:this related post