我需要在数组中找到拥有“最大”权重的类别。我在环境变量中定义权重:
CATEGORY_WEIGHTS = {
"small_standard": 0,
"large_standard": 1,
"small_oversize": 2,
"medium_oversize": 3,
"large_oversize": 4
}
在此示例中,“最大”加权类别将是 large_oversize
。
我正在检查的数组如下所示:
categories = [
"small_oversize",
"large_standard",
"small_standard",
"large_oversize"
]
但是当我这样做时,它没有返回正确的值:
max_category = categories.max_by{ |cat| CATEGORY_WEIGHTS[cat] }
它返回 small_oversize
而不是 large_oversize
。
我哪里误入歧途了?
最佳答案
您在散列中使用符号,但您正尝试使用字符串访问它。将其更改为:
max_category = categories.max_by{|cat| CATEGORY_WEIGHTS[cat.to_sym]}
这里是您可以更简单地做到这一点的方法:
category_weights = {
small_standard: 0,
large_standard: 1,
small_oversize: 2,
medium_oversize: 3,
large_oversize: 4
}
category = category_weights.max_by{|c, w| w}[0]
关于ruby-on-rails - 在 Ruby 中使用 max_by 查找哈希中最大数字的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45826329/