Cinta Cinta - 6 months ago 38
Ruby Question

Get index of hash with hash key

I have this hash with wins, and I'm sorting it based on how many wins a player has ( making a highscore list). Now I'm getting each value out based on a players id. How do I get the index of the value I got. ( So I can get the highscore placement).

#Highscore list.
highscore =

@users.each_with_index do |player, index|
playerTotalGames = @finishedgames.where(log_id:
playerTotalWins = playerTotalGames.where(winner: true)
highscore[] = playerTotalWins.length.to_i

@highscore = highscore.sort_by{ |k, v| v }.reverse.to_h # Sort highscore list


Try this:

index = @highscore.keys.find_index(

But, since it looks like you're going to walk the @highscore hash in its sorted by score order, you could just use with_index

@highscore.each.with_index(1) do |(player_id, score), position|
    # use the block variables as you see fit

The 1 passed to with_index makes the position start from 1 and not the default 0, which might be what you need.