From 9e785b71a05624483a6a1a261e7b5b9d23c85a2c Mon Sep 17 00:00:00 2001 From: David Judd Date: Sun, 26 Jan 2020 10:40:10 -0800 Subject: [PATCH] Recommend Hash#transform_keys & transform_values 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 --- README.adoc | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/README.adoc b/README.adoc index bad270a7a..ad506fcd4 100644 --- a/README.adoc +++ b/README.adoc @@ -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.