带有两个动作的单行`if`返回语句

23t*_*tux 3 ruby coding-style

我正在寻找一种优雅的方式将以下if陈述纳入一行:

if var1.nil?
  log("some message")
  return
end
Run Code Online (Sandbox Code Playgroud)

我喜欢if你可以说的右手声明

return if var1.nil?
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我需要两个动作,但以下不起作用:

log("some message") and return if var1.nil?
Run Code Online (Sandbox Code Playgroud)

有没有办法if在一行的右侧执行两个动作(日志消息和返回)?

saw*_*awa 7

  1. 当你有一个像的方法return,break等等,你可以做(假设你不感兴趣的返回值):

    return log("some message") if var1.nil?
    
    Run Code Online (Sandbox Code Playgroud)
  2. 一种天真的通用方式是:

    (log("some message"); return) if var1.nil?
    
    Run Code Online (Sandbox Code Playgroud)
  3. 但是,如果你不喜欢括号和分号,那么,这样做:如果and不起作用,那么这意味着第一个表达式的返回值是假的,这意味着or应该工作.

    log("some message") or return if var1.nil?
    
    Run Code Online (Sandbox Code Playgroud)

    一般情况下,一个或之间的其他andor将工作,这取决于第一表达的评价值.


Ser*_*sev 5

好吧,不依赖于布尔评估,你总是可以这样做:

(log('some message'); return) if var.nil?
Run Code Online (Sandbox Code Playgroud)

但我个人觉得它比多线版本更不易读

if var1.nil?
  log('some message')
  return
end
Run Code Online (Sandbox Code Playgroud)

modifier-if语法的一个问题是当行太长时你甚至可能都没注意到它.注意:

(log('Something really bad happened while you were doing that thing with our app and we are terribly sorry about that. We will tell our engineers to fix this. Have a good day'); return) if var.nil?
Run Code Online (Sandbox Code Playgroud)