Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change all the keys of a hash by a new set of given keys

Tags:

ruby

hash

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?

like image 600
JCLL Avatar asked Oct 28 '10 15:10

JCLL


People also ask

Can you map a hash in Ruby?

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.

Can a hash key have multiple values?

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.


2 Answers

Assuming you have a Hash which maps old keys to new keys, you could do something like

hsh.transform_keys(&key_map.method(:[])) 
like image 81
Jörg W Mittag Avatar answered Sep 22 '22 11:09

Jörg W Mittag


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} 
like image 36
Santhosh Avatar answered Sep 20 '22 11:09

Santhosh