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.
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
Then, we can check if
params includes all the keys in
This was the code written in the library.
While the above code works, it can be problematic when we have many number
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
which is very useful.
But, let us use
benchmark-ips library which has many more features
compared to inbuilt
The above comparison with benchmark gives us following learnings.
- Getting keys from hash using
#keysmethod 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
#keysand use the same for the further comparison.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox