gpt4 book ai didi

ruby-on-rails - 使用哈希键获取哈希索引

转载 作者:太空宇宙 更新时间:2023-11-03 17:30:47 24 4
gpt4 key购买 nike

我有这个包含获胜次数的哈希值,我正在根据玩家的获胜次数(制作高分列表)对其进行排序。现在我根据玩家 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

最佳答案

试试这个:

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

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

关于ruby-on-rails - 使用哈希键获取哈希索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38285711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com