我在Ruby中有这样的哈希:
hash = {
0..25 => { low_battery_count: 13 },
26..75 => { average_battery_count: 4 },
76..100 => { good_battery_count: 4 }
}
现在,想要的是一个方法(最好是内置的),如果我传递一个值(整数,例如,20、30等),它应该返回这个整数所在范围的值。
我已经使用每种方法解决了它,但现在,我想优化它,甚至更多,不使用each或map方法来降低其复杂性。
例如:
method(3) #=> {:low_battery_count=>13}
method(35) #=> {:average_battery_count=>4}
method(90) #=> {:good_battery_count=>4}
3条答案
按热度按时间ru9i0ody1#
您可以使用
find
来执行此哈希c9x0cxw02#
你需要得到确切的密钥才能从哈希中获取一个值。因此,无论哪种方式,都应该针对可用的键(范围)测试传递的数字。
你可以考虑引入一种优化,它基于为常量分配预定义的范围,并使用大小写相等检查:
kuarbcqp3#
我们可以使用一些内置的方法来做到这一点,但没有任何直接的方法来做到这一点
输出