Ruby: Sorting 2 arrays using values from one of them

后端 未结 2 940
独厮守ぢ
独厮守ぢ 2021-01-25 02:11

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 wan

2条回答
  •  独厮守ぢ
    2021-01-25 02:52

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

    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] 
    

    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.

提交回复
热议问题