Ruby: Better Hash#collect

    After someone asked today (#ruby on irc.freenode.net) how they could preform an action to rename every key in a hash, I was surprised that I actually had to stumble around to figure out a solution. It turns out that Enumerable#collect wan't really designed with (k : v) hashes in mind and only returns an array of modified keys (or values, depending on the case)! Of course, the only other solution was to use Hash#each and iterate over each (k : v) pair and manually add them to a new array, which is hardly ideal.

    So, coming onto the field is my new CollectKeyValue mixin, designed specifically for the Hash class. You can see the source in the gist below.

    The way this works is pretty simple, we simply extend the hash objects that need this functionality (or if you use it frequently in your application, reopen the Hash class and include the module) and then call it like any other iterator. An example is in the gist below.

    It's important to notice that the return value of our block is an array (might as well be a tuple) of the [key, value] pair, this is the standard way of handling multiple returned objects in ruby, since it's the cleanest way to do it. Other than that, the code is as obvious as it gets, we modify the value of each key and spit back out the new (key : value) pair.

    And that's how you do it!

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

I feel like a tard for having

I feel like a tard for having not checked the standard library documentation now.

Stefan Nuxoll
unlocked cell phone

goldleaf

Well , the view of the

Well , the view of the passage is totally correct ,your details is really reasonable and you guy give us valuable informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum! http://www.brfinder.net/

gucci

Well , the view of the passage is totally correct ,your details is really reasonable and you guy give us valuable informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum! http://www.oneor-more.com/

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options