Skip to content

Commit

Permalink
Recommend Hash#transform_keys & transform_values
Browse files Browse the repository at this point in the history
These methods are more readable than the more flexible alternatives when
only keys or only values are being transformed, and also execute more
quickly in microbenchmarks
  • Loading branch information
djudd-stripe authored and bbatsov committed Jan 26, 2020
1 parent 66a521f commit 9e785b7
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions README.adoc
Expand Up @@ -3707,6 +3707,21 @@ username = data['nickname']
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 }
----

=== Ordered Hashes [[ordered-hashes]]

Rely on the fact that as of Ruby 1.9 hashes are ordered.
Expand Down

0 comments on commit 9e785b7

Please sign in to comment.