条件表达式 (Conditional Expressions)

关键字 (Conditional keywords)

  • 永远不要把 then 和多行的 if/unless 搭配使用。
    [link]

    1. # 错误
    2. if some_condition then
    3. ...
    4. end
    5. # 正确
    6. if some_condition
    7. ...
    8. end
  • do 不要和多行的 whileuntil搭配使用。[link]

    1. # 错误
    2. while x > 5 do
    3. ...
    4. end
    5. until x > 5 do
    6. ...
    7. end
    8. # 正确
    9. while x > 5
    10. ...
    11. end
    12. until x > 5
    13. ...
    14. end
  • and, or, 和not 关键词禁用。 因为不值得。 总是用 &&||, 和 ! 来代替。
    [link]

  • 适合用 if/unless 的情况: 内容简单, 条件简单, 整个东西能塞进一行。
    不然的话, 不要用 if/unless
    [link]

    1. # 错误 - 一行塞不下
    2. add_trebuchet_experiments_on_page(request_opts[:trebuchet_experiments_on_page]) if request_opts[:trebuchet_experiments_on_page] && !request_opts[:trebuchet_experiments_on_page].empty?
    3. # 还行
    4. if request_opts[:trebuchet_experiments_on_page] &&
    5. !request_opts[:trebuchet_experiments_on_page].empty?
    6. add_trebuchet_experiments_on_page(request_opts[:trebuchet_experiments_on_page])
    7. end
    8. # 错误 - 这个很复杂,需要写成多行,而且需要注释
    9. parts[i] = part.to_i(INTEGER_BASE) if !part.nil? && [0, 2, 3].include?(i)
    10. # 还行
    11. return if reconciled?
  • 不要把 unlesselse 搭配使用。[link]

    1. # 错误
    2. unless success?
    3. puts 'failure'
    4. else
    5. puts 'success'
    6. end
    7. # 正确
    8. if success?
    9. puts 'success'
    10. else
    11. puts 'failure'
    12. end
  • 避免用多个条件的 unless
    。[link]

    1. # 错误
    2. unless foo? && bar?
    3. ...
    4. end
    5. # 还行
    6. if !(foo? && bar?)
    7. ...
    8. end
  • 条件语句 if/unless/while 不需要圆括号。
    [link]

    1. # 错误
    2. if (x > 10)
    3. ...
    4. end
    5. # 正确
    6. if x > 10
    7. ...
    8. end

三元操作符 (Ternary operator)

  • 避免使用三元操作符 (?:),如果不用三元操作符会变得很啰嗦才用。
    对于单行的条件, 用三元操作符(?:) 而不是 if/then/else/end.[link]

    1. # 错误
    2. result = if some_condition then something else something_else end
    3. # 正确
    4. result = some_condition ? something : something_else
  • 不要嵌套使用三元操作符,换成
    if/else.[link]

    1. # 错误
    2. some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else
    3. # 正确
    4. if some_condition
    5. nested_condition ? nested_something : nested_something_else
    6. else
    7. something_else
    8. end
  • 避免多条件三元操作符。最好判断一个条件。
    [link]

  • 避免拆成多行的 ?: (三元操作符), 用 if/then/else/end 就好了。
    [link]

    1. # 错误
    2. some_really_long_condition_that_might_make_you_want_to_split_lines ?
    3. something : something_else
    4. # 正确
    5. if some_really_long_condition_that_might_make_you_want_to_split_lines
    6. something
    7. else
    8. something_else
    9. end