Ruby编程中的命名风格指南

2019-09-25 09:39:55于海丽

    在定义二元操作符时,把参数命名为 other (<< 与 [] 是这条规则的例外,因为它们的语义不同)。

  def +(other)
   # body omitted
  end

    map 优先于 collect,find 优先于 detect,select 优先于 find_all,reduce 优先于inject,size 优先于 length。以上的规则并不绝定,如果使用后者能提高代码的可读性,那么尽管使用它们。有押韵的方法名(如 collect,detect,inject)继承于 SmallTalk 语言,它们在其它语言中并不是很通用。鼓励使用 select 而不是 find_all 是因为 select 与 reject 一同使用时很不错,并且它的名字具有很好的自解释性。

    不要使用 count 作为 size 的替代。对于 Enumerable 的 Array 以外的对象将会迭代整个集合来
    决定它的尺寸。

 

  # bad
  some_hash.count

  # good
  some_hash.size

    倾向使用 flat_map 而不是 map + flatten 的组合。
    这并不适用于深度大于 2 的数组,举个例子,如果 users.first.songs == ['a', ['b', 'c']] ,则使用 map + flatten 的组合,而不是使用 flat_map 。
    flat_map 将数组变平坦一个层级,而 flatten 会将整个数组变平坦。

  # bad
  all_songs = users.map(&:songs).flatten.uniq

  # good
  all_songs = users.flat_map(&:songs).uniq

    使用 reverse_each 代替 reverse.each。reverse_each 不会分配一个新数组并且这是好事。

  # bad
  array.reverse.each { ... }

  # good
  array.reverse_each { ... }