text
stringlengths
0
444
# bad
hash.has_key?(:test)
hash.has_value?(value)
# good
hash.key?(:test)
hash.value?(value)
----
=== `Hash#each` [[hash-each]]
Use `Hash#each_key` instead of `Hash#keys.each` and `Hash#each_value` instead of `Hash#values.each`.
[source,ruby]
----
# bad
hash.keys.each { |k| p k }
hash.values.each { |v| p v }
hash.each { |k, _v| p k }
hash.each { |_k, v| p v }
# good
hash.each_key { |k| p k }
hash.each_value { |v| p v }
----
=== `Hash#fetch` [[hash-fetch]]
Use `Hash#fetch` when dealing with hash keys that should be present.
[source,ruby]
----
heroes = { batman: 'Bruce Wayne', superman: 'Clark Kent' }
# bad - if we make a mistake we might not spot it right away
heroes[:batman] # => 'Bruce Wayne'
heroes[:supermann] # => nil
# good - fetch raises a KeyError making the problem obvious
heroes.fetch(:supermann)
----
=== `Hash#fetch` defaults [[hash-fetch-defaults]]
Introduce default values for hash keys via `Hash#fetch` as opposed to using custom logic.
[source,ruby]
----
batman = { name: 'Bruce Wayne', is_evil: false }
# bad - if we just use || operator with falsey value we won't get the expected result
batman[:is_evil] || true # => true
# good - fetch works correctly with falsey values
batman.fetch(:is_evil, true) # => false
----
=== Use Hash Blocks [[use-hash-blocks]]
Prefer the use of the block instead of the default value in `Hash#fetch` if the code that has to be evaluated may have side effects or be expensive.
[source,ruby]
----
batman = { name: 'Bruce Wayne' }
# bad - if we use the default value, we eager evaluate it
# so it can slow the program down if done multiple times
batman.fetch(:powers, obtain_batman_powers) # obtain_batman_powers is an expensive call
# good - blocks are lazy evaluated, so only triggered in case of KeyError exception
batman.fetch(:powers) { obtain_batman_powers }
----
=== `Hash#values_at` [[hash-values-at]]
Use `Hash#values_at` when you need to retrieve several values consecutively from a hash.
[source,ruby]
----
# bad
email = data['email']
username = data['nickname']
# good
email, username = data.values_at('email', 'nickname')
----
=== `Hash#transform_keys` and `Hash#transform_values` [[hash-transform-methods]]
Prefer `transform_keys` or `transform_values` over `each_with_object` or `map` when transforming just the keys or just the values of a hash.
[source,ruby]
----
# bad
{a: 1, b: 2}.each_with_object({}) { |(k, v), h| h[k] = v * v }
{a: 1, b: 2}.map { |k, v| [k.to_s, v] }.to_h
# good
{a: 1, b: 2}.transform_values { |v| v * v }
{a: 1, b: 2}.transform_keys { |k| k.to_s }
----