嵌套的`if`语句没有评估操作的结果

Mar*_*n W 0 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, 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
Run Code Online (Sandbox Code Playgroud)

当我在文件不同时运行它时,我得到输出:

Files are different, let's update them.
Run Code Online (Sandbox Code Playgroud)

它运行时FileUtils.cp_r没有任何错误,但它不会告诉文件已成功复制,或运行系统命令.我使用相同的语法来评估FileUtils.identical?,但它不起作用FileUtils.cp_r.

我在哪里错了?

Mar*_*iej 5

FileUtils::cp_r返回nil(在Ruby中是假的)如果复制成功,则会引发错误.它永远不会返回真正的价值,因此将其作为条件是没有意义的.

由于它else现在没有声明,只需删除它if之前.如果您想为自己进行错误处理cp_r,则需要将其包装到一个begin..rescue块中.