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

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

    尽量使用范围或 Comparable#between? 来替换复杂的逻辑比较。

  

 # bad
  do_something if x >= 1000 && x <= 2000

  # good
  do_something if (1000..2000).include?(x)

  # good
  do_something if x.between?(1000, 2000)

    尽量用谓词方法而不是使用 ==。比较数字除外。

   

 # bad
  if x % 2 == 0
  end

  if x % 2 == 1
  end

  if x == nil
  end

  # good
  if x.even?
  end

  if x.odd?
  end

  if x.nil?
  end

  if x.zero?
  end

  if x == 0
  end

    避免使用 BEGIN 区块。

    使用 Kernel#at_exit 。永远不要用 END 区块。

  # bad

  END { puts 'Goodbye!' }

  # good

  at_exit { puts 'Goodbye!' }

    避免使用 flip-flops 。

    避免使用嵌套的条件来控制流程。
    当你可能断言不合法的数据,使用一个防御语句。一个防御语句是一个在函数顶部的条件声明,这样如果数据不合法就能尽快的跳出函数。

   

 # bad
   def compute_thing(thing)
    if thing[:foo]
     update_with_bar(thing)
     if thing[:foo][:bar]
      partial_compute(thing)
     else
      re_compute(thing)
     end
    end
   end

  # good
   def compute_thing(thing)
    return unless thing[:foo]
    update_with_bar(thing[:foo])
    return re_compute(thing) unless thing[:foo][:bar]
    partial_compute(thing)
   end