Collections
Prefer
map
over
collect
.[link]Prefer
detect
overfind
. The use offind
is ambiguous with regard to ActiveRecord’sfind
method -detect
makes
clear that you’re working with a Ruby collection, not an AR object.
[link]Prefer
reduce
overinject
.
[link]Prefer
size
over eitherlength
orcount
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#join
overArray#*
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
Array
that
spans more than 1 line[link]# good
array = [1, 2, 3]
# good
array = [
"car",
"bear",
"plane",
"zoo",
]