Today I came across a really cool method in Ruby’s Hash class. I cannot believe I missed it all these days. Its a class method and its syntax is:
Hash[](args)
Since Ruby is cool, when you do Hash[1,2,3,4]
you actually are doing Hash[](1,2,3,4)
.
So what does it do? It simply creates hashes from Arrays. There are many ways to use this method to create Hashes. We’ll see one by one. The first way is to simply pass an array of elements like this:
Hash[1,2,3,4]
When you do that you get the following Hash as the result:
{1=>2, 3=>4}
Neat. Right? So the important point we must note here is the fact that we should always pass in an array with even length else Ruby will raise odd number of arguments for Hash
error and you probably understand why this is the case.
The second way is to pass an array of key-value pairs and you will get a hash as the result like so:
Hash[1=>2,3=>4] #=> {1=>2,3=>4}
And the third is especially awesome. Take a look for yourself.
Hash[ [ [1,2], [3,4] ] ] #=> {1=>2,3=>4}
This is very useful when you have an ActiveRecord::Relation object and you want to construct a Hash from the records represented by that object. For example, I have a model called ReferenceDatum. I have three attributes – ref_category, ref_name, ref_value
. What if I want to create a hash like {ref_name=>ref_value}
? I could just do something like:
Hash[ReferenceDatum.where(:ref_category=>'mycat').map{|r| [r.ref_name,r.ref_value] }]
There are other ways to do this job as well. But I find this pleasing to the eye and to the mind(barring the part where we do the mapping ofc!).