使用哈希键获取哈希索引

时间:2016-07-09 19:44:40

标签: ruby-on-rails ruby

我有这个哈希与胜利,我根据玩家拥有多少胜利(制作高分榜单)对其进行排序。现在我根据玩家ID获取每个价值。如何获得我得到的值的索引。 (所以我可以得到高分榜)。

#Highscore list.
highscore = Hash.new

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

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

2 个答案:

答案 0 :(得分:3)

试试这个:

index = @highscore.keys.find_index(player.id)

但是,既然看起来你要按照排序顺序走@highscore哈希,你就可以使用with_index

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

传递给1的{​​{1}}使得位置从1开始而不是默认值0,这可能是您需要的。

答案 1 :(得分:2)

为了进一步优化您的代码,(假设您没有在其他地方使用playerTotalGames变量),您可以playerTotalWins = @finishedgames.where(log_id: player.id, winner: true)