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.

Advertisements

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

  1. 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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s