我试图找到确定给定整数在哪个范围内的最佳方法. 以此哈希为例: score_levels = { 1 = {'name' = 'Beginner', 'range' = 0..50}, 2 = {'name' = 'Intermediate', 'range' = 51..70}, 3 = {'name' = 'Pro', 'range' = 71..85},
以此哈希为例:
score_levels = { 1 => {'name' => 'Beginner', 'range' => 0..50}, 2 => {'name' => 'Intermediate', 'range' => 51..70}, 3 => {'name' => 'Pro', 'range' => 71..85}, 4 => {'name' => 'Expert', 'range' => 86..96}, 5 => {'name' => 'Master', 'range' => 97..100} }
我希望在得分时运行不同的逻辑,例如:
case score when score_levels[1]['range'] level_counters[1] += 1 when score_levels[2]['range'] level_counters[2] += 1 when score_levels[3]['range'] level_counters[3] += 1 end
有更通用的方法吗?
也许是这种精神的东西:
score_levels.each |key, val| {if val['range'].member?(score) then level_counters[key] += 1 }
谢谢!
就在这里.level_counters[score_levels.find{|_, h| h["range"].include?(score)}.first] += 1