Brennan Dunn Web Application Developer

Thoughts, ramblings, and other sundry topics.


Hash#hashmap, having 0 replies


One thing that always annoyed me about Ruby's enumerable methods is that they are very partial toward arrays. Sure, they play nicely with hashes or any instance that is setup to work with Enumerable, but still - hash goes in, array comes out.

I had the challenge of wanting to perform operations on the values of a given hash, and easily return a hash with just the values transformed. So I created a Hash method called hashmap.

class Hash
  # Translate the keys/values of a hash and return a new hash
  # {:one => 'one', :two => 'two'}.hashmap { |k,v| [k.to_s.reverse, v.upcase] }  # => { 'eno' => 'ONE', 'owt' => 'TWO' }      
  def hashmap(&block)
    inject({}) do |hsh, (key, value)|
      arr = yield(key, value)
      hsh[arr.first] = arr.last ; hsh
    end
  end
end

Enjoy!

Name
Email
Website
 
Alert you when new comments are posted?