How do I change all the keys of a hash by a new set of given keys?
Is there a way to do that elegantly?
Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.
Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.
Assuming you have a Hash
which maps old keys to new keys, you could do something like
hsh.transform_keys(&key_map.method(:[]))
Ruby 2.5 has Hash#transform_keys! method. Example using a map of keys
h = {a: 1, b: 2, c: 3} key_map = {a: 'A', b: 'B', c: 'C'} h.transform_keys! {|k| key_map[k]} # => {"A"=>1, "B"=>2, "C"=>3}
You can also use symbol#toproc shortcut with transform_keys Eg:
h.transform_keys! &:upcase # => {"A"=>1, "B"=>2, "C"=>3}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With