Monday, April 11, 2011

Ways to map hashes

In Ruby, Hashes haven't the map or map! method; it's for Arrays.

However, sometimes we need to do something with the keys or the elements of a Hash. Here I show some ways to do that:

1. Through each_key or each_pair (first natural options, from reference):
hash.each_key  { |k| hash[k] = some_fun(hash[k]) }
hash.each      { |k, v| hash[k] = some_fun(v) }
hash.each_pair { |k, v| hash[k] = some_fun(v) }

2. Through merge (inspired here):
hash.merge(hash) { |k, ov| sume_fun(ov) }

3. Here a way to modify the keys (from here):
Hash[*hash.map{|key,value| [key.upcase, value]}.flatten]

4. A way to work with hashes sorted by keys (which I published here):
hash.keys.sort.each { |k| puts k + " => " + hash[k] + "
\n" }

No comments:

Post a Comment