/ RUBY

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,

mandatory_keys = [:from, :to, :caller_id, :call_type]

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

params = {a: 4, b: 5, b: 4, to: 'akshay'}

Then, we can check if params includes all the keys in mandatory_keys in following way.

mandatory_keys.all?{|key| params.keys.include?(key)}

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

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee