我有以下哈希
hash = {"CLIENT1"=>"12.89", "CLIENT2"=>"14.36", "CLIENT3"=>"12.57", "CLIENT4"=>"11.02", "CLIENT5"=>"12.53", "CLIENT6"=>"12.49", "CLIENT7"=>"12.32", "CLIENT8"=>"11.47", "CLIENT9"=>"13.60", "CLIENT10"=>"13.11", "CLIENT11"=>"8.43", "CLIENT12"=>"11.41", "CLIENT13"=>"11.06", "CLIENT14"=>"11.47", "CLIENT15"=>"6.53", "CLIENT16"=>"12.36", "CLIENT17"=>"11.86", "CLIENT18"=>"12.93", "CLIENT19"=>"11.54", "CLIENT20"=>"9.93"}
当我hash.values.max
时,我得到9.93 - 这是不正确的。 hash.values.min
也给出了错误的11.02结果
任何人都能告诉我可能出错的地方吗?如果我向只有10个客户端的哈希发出相同的命令,它将按预期工作。
答案 0 :(得分:4)
你需要将字符串转换为浮点数(headlapper,嗯?)。
a = hash.values.map(&:to_f)
#=> [12.89, 14.36, 12.57, 11.02, 12.53, 12.49, 12.32, 11.47, 13.6, 13.11,
# 8.43, 11.41, 11.06, 11.47, 6.53, 12.36, 11.86, 12.93, 11.54, 9.93]
a.max => 14.36
a.min => 6.53
"9.1" > "10.2" #=> true
9.1 > 10.2 #=> false
答案 1 :(得分:1)
我将使用#minmax_by
方法执行以下操作: -
min, max = hash.minmax_by { |_,v| v.to_f }.map(&:last)
min # => "6.53"
max # => "14.36"