Interesting Methods to Work with Ruby Hashes in A Better Way
Ruby hashes are one of the most powerful data structures of Ruby. It comes with many inbuilt methods which we are using on a daily basis and still, there are many other options about which we are not aware of.
In this tutorial, I am going to share some bad-good-better solutions for using Ruby hashes.
By using such advance or shorthand ways, we can make our code more readable, easy to debug and reuse.
Here I am going to share some code snippets of such usage and will see how we can make it better or best.
Point – 1: No need to explicitly check whether particular params is present or not. We can directly compare params with our comparison statements.
Point – 2: While merging keys and values to some other hash, we usually add curly braces. Actually, that is redundant. No need for such curly braces. We can directly do it like below.
It will work as expected.
Point – 3: It is always problematic while working with nested hash and we are not certain about our data.
Let’s assume that we have a column named properties and it stores hash data like given below:
As mentioned above, there are different examples that you may have to handle. In general, we simply add conditions before accessing the name key from the hash.
As mentioned above, there are different examples that you may have to handle. In general, we simply add conditions before accessing the name key from a hash.
As you know the principle, Tell, Don’t Ask, Instead of questioning for presence we should directly access the value of name. If you want to verify the presence of the key and then returning the value of the same, we can use the #dig method:
The hash#dig method will not throw an error and returns nil, in case of key not available. The behavior of ruby methods Hash#try and Hash#dig are same but when applying on nested hash, dig method is more readable and looks decent then Hash#try method.
Point – 4: Now let’s consider a scenario where you have to fetch details from the hash and if it is not present then return some default value. For example here, we have a hash of employee details containing their name and city. If any employee’s details not present and you want that your query returns default value then you can use Hash#fetch method.
I suggest using a hash cautiously in your code. Try to use the methods explained above to make your code more readable and efficient.
Have a happy coding!
At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.
Consulting is free – let us help you grow!
Choose Your Language
- Digital Marketing
- IT Consulting
- Project Management