条件表达式 (Conditional Expressions)

条件表达式 (Conditional Expressions)

关键字 (Conditional keywords)

  • 永远不要把 then 和多行的 if/unless 搭配使用。
    [link]
  #  错误
  if some_condition then
    ...
  end

  #  正确
  if some_condition
    ...
  end
  • do 不要和多行的 while 或 until搭配使用。[link]
  #  错误
  while x > 5 do
    ...
  end

  until x > 5 do
    ...
  end

  #  正确
  while x > 5
    ...
  end

  until x > 5
    ...
  end
  • and, or, 和not 关键词禁用。 因为不值得。 总是用 &&, ||, 和 ! 来代替。
    [link]

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

  #  错误 - 一行塞不下
  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?

  #  还行
  if request_opts[:trebuchet_experiments_on_page] &&
       !request_opts[:trebuchet_experiments_on_page].empty?

    add_trebuchet_experiments_on_page(request_opts[:trebuchet_experiments_on_page])
  end

  #  错误 - 这个很复杂,需要写成多行,而且需要注释
  parts[i] = part.to_i(INTEGER_BASE) if !part.nil? && [0, 2, 3].include?(i)

  #  还行
  return if reconciled?
  • 不要把 unless 和 else 搭配使用。[link]
  #  错误
  unless success?
    puts 'failure'
  else
    puts 'success'
  end

  #  正确
  if success?
    puts 'success'
  else
    puts 'failure'
  end
  • 避免用多个条件的 unless
    。[link]
    #  错误
    unless foo? && bar?
      ...
    end

    #  还行
    if !(foo? && bar?)
      ...
    end
  • 条件语句 if/unless/while 不需要圆括号。
    [link]
  #  错误
  if (x > 10)
    ...
  end

  #  正确
  if x > 10
    ...
  end

三元操作符 (Ternary operator)

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

  #  正确
  result = some_condition ? something : something_else
  • 不要嵌套使用三元操作符,换成
    if/else.[link]
  #  错误
  some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else

  #  正确
  if some_condition
    nested_condition ? nested_something : nested_something_else
  else
    something_else
  end
  • 避免多条件三元操作符。最好判断一个条件。
    [link]

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

  #  错误
  some_really_long_condition_that_might_make_you_want_to_split_lines ?
    something : something_else

  #  正确
  if some_really_long_condition_that_might_make_you_want_to_split_lines
    something
  else
    something_else
  end