红宝石:从其中一人用排序值2数组 [英] Ruby: Sorting 2 arrays using values from one of them

查看:104
本文介绍了红宝石:从其中一人用排序值2数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建红宝石一个简单的游戏,我有两个数组存储高分: $ HS_Points $ HS_Names 。我保存在两个文件中的高分,而我想EN code点位(点转换与 .to_s(23))。我想降序排列的名字和分数进行排序,并将其限制为10。所以,我需要:

I'm creating a simple game in ruby, and I have two arrays storing high score: $HS_Points and $HS_Names. I'm saving high score in two files, and I wanted to encode points a bit (the points are converted with .to_s(23)). I wanted to sort names and scores in descending order and limit them to 10. So, I need to:


  • 检查点得分的球员数量是否比高分(索引0〜9)点量较高。

  • 如果收到的分数足以使玩家在排名前10位,把分和名字的那个地方,一个地方推其他了。

简单 points_array.sort 不会做,因为它只会在积分排序,留下姓名,以便他们。

Simple points_array.sort won't do, because it will just sort the points, leaving the names in order they were.

任何想法如何解决这个问题?我想请继续回答尽可能简单。

Any ideas how to solve that problem? I'd please to keep answer as simple as possible.

推荐答案

不要存放的名字,并在不同的变量分数;他们绑在一起,所以他们的数据应该togeher捆绑。

Don't store the names and the scores in separate variables; they're tied together, so their data should be tied togeher.

尝试,比如说,$高分,这是哈希与数组:name元素和一个:价值元素,如:

Try, say, $HighScores, which is an array of hashes with a :name element and a :value element, like:

$HighScores = [  
   { :name => "Bob", :score => 234 },
   { :name => "Mark", :score => 2 },   
]

然后你就可以添加一个高分:

Then you can add a high score:

$HighScores << { :name => "New Guy", :score => 50000 }

然后再对它们进行排序,并采取十大在一条语句:

and then re-sort them and take the top 10 in one statement:

$HighScores = $HighScores.sort { |a,b| b[:score] <=> a[:score] }[0,10] 

这仍然会工作,如果分数基带23 codeD。 (但你为什么这样做?)

This will still work if the scores are base-23 encoded. (but why are you doing that?)

您应该也可能将它们保存到一个文件中。为了更轻松,可以考虑使用元帅模块。

You should probably also save them to a single file. To make that easier, consider using the Marshal module.

这篇关于红宝石:从其中一人用排序值2数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆