Collections
Collections
-
Prefer
mapover
collect.[link] -
Prefer
detectoverfind. The use offind
is ambiguous with regard to ActiveRecord’sfindmethod -detectmakes
clear that you’re working with a Ruby collection, not an AR object.
[link] -
Prefer
reduceoverinject.
[link] -
Prefer
sizeover eitherlengthorcount
for performance reasons.[link] -
Prefer literal array and hash creation
notation unless you need to pass parameters to their constructors.
[link]
# bad
arr = Array.new
hash = Hash.new
# good
arr = []
hash = {}
# good because constructor requires parameters
x = Hash.new { |h, k| h[k] = {} }
- Favor
Array#joinoverArray#*for clarity.
[link]
# bad
%w(one two three) * ', '
# => 'one, two, three'
# good
%w(one two three).join(', ')
# => 'one, two, three'
- Use symbols instead of strings as hash keys.
[link]
# bad
hash = { 'one' => 1, 'two' => 2, 'three' => 3 }
# good
hash = { :one => 1, :two => 2, :three => 3 }
- Relatedly, use plain symbols instead of string
symbols when possible.[link]
# bad
:"symbol"
# good
:symbol
- Use
Hash#key?instead of
Hash#has_key?andHash#value?instead ofHash#has_value?. According
to Matz, the longer forms are considered deprecated.
[link]
# bad
hash.has_key?(:test)
hash.has_value?(value)
# good
hash.key?(:test)
hash.value?(value)
- Use multi-line hashes when it makes the code
more readable, and use trailing commas to ensure that parameter changes
don’t cause extraneous diff lines when the logic has not otherwise changed.
[link]
hash = {
:protocol => 'https',
:only_path => false,
:controller => :users,
:action => :set_password,
:redirect => @redirect_url,
:secret => @secret,
}
- Use a trailing comma in an
Arraythat
spans more than 1 line[link]
# good
array = [1, 2, 3]
# good
array = [
"car",
"bear",
"plane",
"zoo",
]
