Ruby 嵌套的'if'语句不计算操作结果
我正在临时目录中生成一个文件。 如果要生成的文件与现有文件不同,则我不想更新它,而是运行命令。如果是一样的,那我什么也做不了 我的代码如下所示:Ruby 嵌套的'if'语句不计算操作结果,ruby,Ruby,我正在临时目录中生成一个文件。 如果要生成的文件与现有文件不同,则我不想更新它,而是运行命令。如果是一样的,那我什么也做不了 我的代码如下所示: errstatus = 0 if FileUtils.identical?('/var/tmp/newfile', '/var/tmp/originalfile') $stderr.puts "Files are the same, nothing to do" else $stderr.puts "Files are different, l
errstatus = 0
if FileUtils.identical?('/var/tmp/newfile', '/var/tmp/originalfile')
$stderr.puts "Files are the same, nothing to do"
else
$stderr.puts "Files are different, let's update them."
if FileUtils.cp_r '/var/tmp/newfile', '/var/tmp/originalfile'
$stderr.puts "File copied successfully."
if system('systemcommand1 here')
$stderr.puts "command ran OK"
if system('systemcommand2 here')
$stderr.puts "next command ran ok"
else
$stderr.puts "command 2 failed"
errstatus = 1
end
else
$stderr.puts "command 1 failed"
errstatus = 1
end
end
end
当我在文件不同的情况下运行它时,我会得到以下输出:
Files are different, let's update them.
它与FileUtils.cp\r
一起运行,没有任何错误,但不会告诉您文件复制成功,也不会运行系统命令。我使用了相同的语法来计算FileUtils.idential?
,但它不适用于FileUtils.cp\u r
我在这里哪里出错了?可能是因为
if FileUtils.cp\r'/var/tmp/newfile',“/var/tmp/originalfile'
没有else
子句,所以如果它返回false
或抛出异常,则不会输入if。可能是因为if FileUtils.cp\r'/var/tmp/newfile',“/var/tmp/originalfile”
没有else
子句,因此如果它返回false
或抛出异常,则不会输入if。FileUtils::cp\u r
返回nil
(在Ruby中是falsy),如果复制成功,则会引发错误。它永远不会返回真实值,因此将其作为条件是没有意义的
由于它现在没有
else
语句,只需删除它前面的if
。如果要对cp\r
进行错误处理,则需要将其包装到begin..rescue
块中。FileUtils::cp\u r
返回nil
(在Ruby中为falsy)。如果复制成功,则会引发错误。它永远不会返回真实值,因此将其作为条件是没有意义的
由于它现在没有
else
语句,只需删除它前面的if
。如果您希望对cp\r
进行错误处理,则需要将其包装到begin..rescue
块中。感谢您的快速响应。这让我走了一段路。。。正如Marcin在下面解释的,如果cp_r有效,它将返回一个nil,因此这种错误检查方法永远不会起作用,这要感谢它的快速响应。这让我走了一段路。。。正如Marcin在下面解释的那样,如果cp_r有效,它将返回一个nil,因此这种错误检查方法永远不会完美工作,这非常有帮助。谢谢太好了,这很有帮助。谢谢