集合 (Collections)

  • 尽量用 map 而不是 collect。[link]

  • 尽量用 detect 而不是 findfind
    容易和 ActiveRecord 的 find 搞混 - detect 则是明确的说明了
    是要操作 Ruby 的集合, 而不是 ActiveRecord 对象。
    [link]

  • 尽量用 reduce 而不是 inject
    [link]

  • 尽量用 size, 而不是 length 或者 count, 出于性能理由。[link]

  • 尽量用数组和 hash 字面量来创建,
    而不是用 new。 除非你需要传参数。
    [link]

    1. # 错误
    2. arr = Array.new
    3. hash = Hash.new
    4. # 正确
    5. arr = []
    6. hash = {}
    7. # 正确, 因为构造函数需要参数
    8. x = Hash.new { |h, k| h[k] = {} }
  • 为了可读性倾向于用 Array# join 而不是 Array# *
    [link]

    1. # 错误
    2. %w(one two three) * ', '
    3. # => 'one, two, three'
    4. # 正确
    5. %w(one two three).join(', ')
    6. # => 'one, two, three'
  • 用 符号(symbols) 而不是 字符串(strings) 作为 hash keys。
    [link]

    1. # 错误
    2. hash = { 'one' => 1, 'two' => 2, 'three' => 3 }
    3. # 正确
    4. hash = { :one => 1, :two => 2, :three => 3 }
  • 如果可以的话, 用普通的 symbol 而不是字符串 symbol。[link]

    1. # 错误
    2. :"symbol"
    3. # 正确
    4. :symbol
  • Hash# key? 而不是 Hash# has_key?
    Hash# value? 而不是 Hash# has_value?.
    根据 Matz 的说法, 长一点的那种写法在考虑要废弃掉。
    [link

    1. # 错误
    2. hash.has_key?(:test)
    3. hash.has_value?(value)
    4. # 正确
    5. hash.key?(:test)
    6. hash.value?(value)
  • 用多行 hashes 使得代码更可读, 逗号放末尾。
    [link]

    1. hash = {
    2. :protocol => 'https',
    3. :only_path => false,
    4. :controller => :users,
    5. :action => :set_password,
    6. :redirect => @redirect_url,
    7. :secret => @secret,
    8. }
  • 如果是多行数组,用逗号结尾。[link]

    1. # 正确
    2. array = [1, 2, 3]
    3. # 正确
    4. array = [
    5. "car",
    6. "bear",
    7. "plane",
    8. "zoo",
    9. ]