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.


Share:


Comments

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 :-)
    /Lasse

Leave a Reply to Lasse Bunk Cancel reply

Your email address will not be published. Required fields are marked *