Ruby do not use keys method on a hash in loop
Today, I was looking at the internal working of a gem. While working on the same, I came across the code where the network calls were being made and it had to check if the response params has some set of keys.
Problem
Let’s take an example to illustrate this. Let’s say we have some params as,
And let’s say we need to check if these all keys are present in the response.
Let’s say we have response params in a variable called params
Then, we can check if params
includes all the keys in mandatory_keys
in
following way.
This was the code written in the library.
While the above code works, it can be problematic when we have many number
of mandatory_keys
Benchmark
Whenever we are unsure of how much time a particular code block
may take in Ruby, Benchmark
it to test it’s behavior.
Ruby comes up with Benchmarking library benchmark
,
which is very useful.
But, let us use benchmark-ips
library which has many more features
compared to inbuilt benchmark
library.
Conclusion
The above comparison with benchmark gives us following learnings.
- Getting keys from hash using
#keys
method returns a new array by inserting keys of the hash to it. - While the other approach makes sure that we collect those keys in a single
method call to
#keys
and use the same for the further comparison.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox