mardi 30 août 2022

Searching using a single integer in a hash whose keys are ranges in Ruby

I have this hash in Ruby:

hash = {
   0..25  => { low_battery_count:     13 }, 
  26..75  => { average_battery_count:  4 }, 
  76..100 => { good_battery_count:     4 }
}

Now, what is want is a method (preferably a built-in one) in which if I pass a value (integer e.g. 20, 30, etc), it should return me the value against the range in which this integer lies.

I have already solved it using each method but now, I want to optimize it, even more, to do it without each or map methods to reduce its complexity.

For Example:

method(3) #=> {:low_battery_count=>13}
method(35) #=> {:average_battery_count=>4}
method(90) #=> {:good_battery_count=>4}

Aucun commentaire:

Enregistrer un commentaire