集合 (Collections)

集合 (Collections)

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

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

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

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

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

  #  错误
  arr = Array.new
  hash = Hash.new

  #  正确
  arr = []
  hash = {}

  #  正确, 因为构造函数需要参数
  x = Hash.new { |h, k| h[k] = {} }
  • 为了可读性倾向于用 Array# join 而不是 Array# *。
    [link]
  #  错误
  %w(one two three) * ', '
  #  => 'one, two, three'

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

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

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

  #  正确
  hash.key?(:test)
  hash.value?(value)
  • 用多行 hashes 使得代码更可读, 逗号放末尾。
    [link]
  hash = {
    :protocol => 'https',
    :only_path => false,
    :controller => :users,
    :action => :set_password,
    :redirect => @redirect_url,
    :secret => @secret,
  }
  • 如果是多行数组,用逗号结尾。[link]
  #  正确
  array = [1, 2, 3]

  #  正确
  array = [
    "car",
    "bear",
    "plane",
    "zoo",
  ]