Ruby编程中的语法使用风格推荐

2019-09-25 09:40:00王冬梅

    不要使用 if x; ...。使用三元操作运算代替。

    利用 if and case 是表达式这样的事实它们返回一个结果。

  # bad
  if condition
   result = x
  else
   result = y
  end

  # good
  result =
   if condition
    x
   else
    y
   end

    在 one-line cases 的时候使用 when x then ...。替代的语法when x: xxx已经在Ruby 1.9中移除。

    不要使用when x; ...。查看上面的规则。

    使用 ! 替代 not.

    

# 差 - 因为操作符有优先级,需要用括号。
  x = (not something)

  # good
  x = !something

  避免使用 !!.

  # bad
  x = 'test'
  # obscure nil check
  if !!x
   # body omitted
  end

  x = false
  # double negation is useless on booleans
  !!x # => false

  # good
  x = 'test'
  unless x.nil?
   # body omitted
  end

    The and and or keywords are banned. It's just not worth
    it. Always use && and || instead.

    and 和 or 这两个关键字被禁止使用了。它名不符实。总是使用 && 和 || 来取代。

   

 # bad
  # boolean expression
  if some_condition and some_other_condition
   do_something
  end

  # control flow
  document.saved? or document.save!

  # good
  # boolean expression
  if some_condition && some_other_condition
   do_something
  end

  # control flow

    document.saved? || document.save!

    避免多行的 ? :(三元操作符);使用 if/unless 来取代。

    单行主体喜欢使用 if/unless 修饰符。另一个好方法是使用 &&/|| 控制流程。

    

# bad
  if some_condition
   do_something
  end

  # good
  do_something if some_condition

  # another good option
  some_condition && do_something

    布尔表达式使用&&/||, and/or用于控制流程。(经验Rule:如果你必须使用额外的括号(表达逻辑),那么你正在使用错误的的操作符。)

   

 # boolean expression
  if some_condition && some_other_condition
   do_something
  end

  # control flow
  document.save? or document.save!

    避免多行?:(三元操作运算),使用 if/unless 替代。

    在单行语句的时候喜爱使用 if/unless 修饰符。另一个好的选择就是使 and/or 来做流程控制。

   

 # bad
  if some_condition
   do_something
  end

  # good
  do_something if some_condition

  # another good option
  some_condition and do_something

    永远不要使用 unless 和 else 组合。将它们改写成肯定条件。