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