在Ruby中使用哈希中的单个整数进行搜索,其键是范围

camsedfj  于 12个月前  发布在  Ruby
关注(0)|答案(3)|浏览(95)

我在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}
ru9i0ody

ru9i0ody1#

您可以使用find来执行此哈希

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
c9x0cxw0

c9x0cxw02#

你需要得到确切的密钥才能从哈希中获取一个值。因此,无论哪种方式,都应该针对可用的键(范围)测试传递的数字。
你可以考虑引入一种优化,它基于为常量分配预定义的范围,并使用大小写相等检查:

SMALL = 0..25
MEDUIM = 26..75
LARGE = 76..100

def method(n)
  case n
  when SMALL then data[SMALL]
  when MEDUIM then data[MEDUIM]
  when LARGE then data[LARGE]
  end
end

def data
  @data ||= {
    SMALL => { low_battery_count: 13 },
    MEDUIM => { average_battery_count: 4 },
    LARGE =>{ good_battery_count: 4 }
  }
end

method(25)
=> {:low_battery_count=>13}
method(44)
=> {:average_battery_count=>4}
method(76)
=> {:good_battery_count=>4}
kuarbcqp

kuarbcqp3#

我们可以使用一些内置的方法来做到这一点,但没有任何直接的方法来做到这一点

class Hash
  def value_at_key_range(range_member)
    keys.select{ |range| range.include?(range_member) }.map{ |key| self[key]}
  end
end

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

p hash.value_at_key_range(10)

输出

[{:low_battery_count=>13}]

相关问题