I’m trying to determine a rank for each key in a hash against the other keys based on it’s value. The value is numeric. Ranks can be repeated (i.e. 3 keys can tie for first place). This works, but is ugly.
standings.sort_by {|k, v| v}.reverse!
prev_k = nil
standings.each_with_index do |(k, v), i|
if i == 0
k.rank = 1
elsif v == standings[prev_k]
k.rank = prev_k.rank
else
k.rank = prev_k.rank + 1
end
prev_k = k
end
Give this a try:
I’m not sure it’s any prettier, but it’s a bit more compact, carries fewer loop variables, and has no conditionals.