text
stringlengths 0
444
|
|---|
Use `Set` instead of `Array` when dealing with unique elements.
|
`Set` implements a collection of unordered values with no duplicates.
|
This is a hybrid of ``Array``'s intuitive inter-operation facilities and ``Hash``'s fast lookup.
|
=== Symbols as Keys [[symbols-as-keys]]
|
Prefer symbols instead of strings as hash keys.
|
[source,ruby]
|
----
|
# bad
|
hash = { 'one' => 1, 'two' => 2, 'three' => 3 }
|
# good
|
hash = { one: 1, two: 2, three: 3 }
|
----
|
=== No Mutable Keys [[no-mutable-keys]]
|
Avoid the use of mutable objects as hash keys.
|
=== Hash Literals [[hash-literals]]
|
Use the Ruby 1.9 hash literal syntax when your hash keys are symbols.
|
[source,ruby]
|
----
|
# bad
|
hash = { :one => 1, :two => 2, :three => 3 }
|
# good
|
hash = { one: 1, two: 2, three: 3 }
|
----
|
=== Hash Literal Values
|
Use the Ruby 3.1 hash literal value syntax when your hash key and value are the same.
|
[source,ruby]
|
----
|
# bad
|
hash = { one: one, two: two, three: three }
|
# good
|
hash = { one:, two:, three: }
|
----
|
=== Hash Literal as Last Array Item [[hash-literal-as-last-array-item]]
|
Wrap hash literal in braces if it is a last array item.
|
[source,ruby]
|
----
|
# bad
|
[1, 2, one: 1, two: 2]
|
# good
|
[1, 2, { one: 1, two: 2 }]
|
----
|
=== No Mixed Hash Syntaxes [[no-mixed-hash-syntaxes]]
|
Don't mix the Ruby 1.9 hash syntax with hash rockets in the same hash literal.
|
When you've got keys that are not symbols stick to the hash rockets syntax.
|
[source,ruby]
|
----
|
# bad
|
{ a: 1, 'b' => 2 }
|
# good
|
{ :a => 1, 'b' => 2 }
|
----
|
=== Avoid Hash[] constructor [[avoid-hash-constructor]]
|
`Hash::[]` was a pre-Ruby 2.1 way of constructing hashes from arrays of key-value pairs,
|
or from a flat list of keys and values. It has an obscure semantic and looks cryptic in code.
|
Since Ruby 2.1, `Enumerable#to_h` can be used to construct a hash from a list of key-value pairs,
|
and it should be preferred. Instead of `Hash[]` with a list of literal keys and values,
|
just a hash literal should be preferred.
|
[source,ruby]
|
----
|
# bad
|
Hash[ary]
|
Hash[a, b, c, d]
|
# good
|
ary.to_h
|
{a => b, c => d}
|
----
|
=== `Hash#key?` [[hash-key]]
|
Use `Hash#key?` instead of `Hash#has_key?` and `Hash#value?` instead of `Hash#has_value?`.
|
[source,ruby]
|
----
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.