A hash map method that returns a hash


I’ve just released another gem, this one extends Hash to contain another method called hmap. This solves a problem I face ofter: how to run a map in a hash that returns another hash, for example:

{:a => 1, :b => 2, :c => 3}

being converted into

{:a => 2, :b => 3, :c => 4}

With hmap it’s easy:

hash.hmap { |a,b| {a => b + 1} }

It also works with arrays, but you must make sure the array you return always contains two and only two elements:

hash.hmap { |a,b| [a, b + 1] }

And that’s all, quite a simple piece of code, but now it’s re-usable and well tested.

One response to “A hash map method that returns a hash”

  1. Lasse Bunk Avatar

    Or you could use:

    hash = {:a => 1, :b => 2, :c => 3}
    Hash[*hash.map{ |key, value| [key, value + 1] }.flatten]

    That’s a longer version but you can use it without the gem :-)

Leave a Reply

You may also like:

Hi, I'm Pablo, this is my web site. You can follow me or connect with me:

Or get new content delivered directly to your inbox.

Join 4,048 other subscribers

I'm writing a book

Stack of copies of How to Hire and Manage Remote Teams

How to Hire and Manage Remote Teams, where I distill all the techniques I've been using to build and manage distributed teams for the past 10 years.

I write about:

announcement blogging book book review book reviews books building Sano Business C# Clojure ClojureScript Common Lisp database Debian Esperanto Git ham radio history idea Java Keep on Posting Kubuntu Lisp Non-Fiction OpenID programming Python Radio Society of Great Britain Rails rant re-frame release Ruby Ruby on Rails Sano science science fiction security self-help Star Trek startups technology Ubuntu web WordPress

I've been writing for a while:


%d bloggers like this: