Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-hash

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}

Solution

  • You can use find for this hash

    BATTERIES = {
      0..25  => { low_battery_count:     13 }, 
      26..75  => { average_battery_count:  4 }, 
      76..100 => { good_battery_count:     4 }
    }
    
    def get_batteries_count(value)
      BATTERIES.find { |range, _| range.include?(value) }&.last
    end
    
    get_batteries_count(3) #=> {:low_battery_count=>13}
    get_batteries_count(35) #=> {:average_battery_count=>4}
    get_batteries_count(90) #=> {:good_battery_count=>4}
    get_batteries_count(2000) #=> nil