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.