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

时间:2015-12-21 20:45:01

标签: ruby coding-style

我正在寻找一种优雅的方式将以下if语句放入一行:

if var1.nil?
  log("some message")
  return
end

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

return if var1.nil?

在这种情况下,我需要两个操作,但以下操作无效:

log("some message") and return if var1.nil?

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

2 个答案:

答案 0 :(得分:6)

  1. 当您使用returnbreak等方法时,您可以这样做(假设您对返回值不感兴趣):

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

    (log("some message"); return) if var1.nil?
    
  3. 但如果您不喜欢括号和分号,那么,请执行以下操作:如果and不起作用,那么这意味着第一个表达式的返回值为falsy,这意味着{{ 1}}应该工作。

    or

    通常,log("some message") or return if var1.nil? and之间的一个或另一个可以使用,具体取决于第一个表达式的评估值。

答案 1 :(得分:5)

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

(log('some message'); return) if var.nil?

但我个人认为它比多线版

的可读性低得多
if var1.nil?
  log('some message')
  return
end

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?