gpt4 book ai didi

ruby - 检查范围集合中的整数

转载 作者:数据小太阳 更新时间:2023-10-29 07:47:38 25 4
gpt4 key购买 nike

我正在尝试找到确定给定整数在哪个范围内的最佳方法。以此哈希为例:

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 }

谢谢!

最佳答案

由于范围不重叠并无缝覆盖 0..100 - 您不需要明确的范围,而是像这样的东西:

score_levels = [
{id:1, name: 'Beginner', max_score:50},
{id:2, name: 'Intermediate', max_score:70},
{id:3, name: 'Pro', max_score:85},
{id:4, name: 'Expert', max_score:96},
{id:5, name: 'Master', max_score:100}
].sort_by{|v| v[:max_score]}

sort_by 是可选的,但留在那里表示应该对数组进行排序

并找到自己(假设分数不超过最大值并且总能找到)

level_counters[ score_levels.find{|v| score <= v[:max_score]}[:id] ] += 1

关于ruby - 检查范围集合中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34512023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com