Ruby: Sorting 2 arrays using values from one of them

后端 未结 2 943
独厮守ぢ
独厮守ぢ 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:44

    Something like this?

    names = ['Alice', 'Bob', 'Carol']
    points = [22, 11, 33]
    

    Zip

    You may want the Array#zip method:

    pairs = names.zip(points)
    #=> [["Alice", 22], ["Bob", 11], ["Carol", 33]]
    

    Sort

    To sort by an array field, compare two fields of the pair.

    Sort by name:

    pairs.sort{|x,y| x[0] <=> y[0] }  
    #=> [["Alice", 22], ["Bob", 11], ["Carol", 33]]
    

    Sort by score:

    pairs.sort{|x,y| x[1] <=> y[1] }  
    #=> [["Bob", 11], ["Alice", 22], ["Carol", 33]]
    

    Sort By

    Another way to sort is the #sort_by method instead of a comparison block (thanks to Niklas B.)

    Sort by name:

    pairs.sort_by(&:first) 
    #=> [["Alice", 22], ["Bob", 11], ["Carol", 33]]
    

    Sort by score:

    pairs.sort_by(&:last)
    #=> [["Bob", 11], ["Alice", 22], ["Carol", 33]]
    

    Select

    To select just the players above a high score:

    pairs.select{|x| x[1] >20 }
    #=> [["Alice", 22], ["Carol", 33]]
    

    Unzip

    To unzip:

    pairs.map(&:first)
    #=> ["Alice", "Bob", "Carol"]
    
    pairs.map(&:last)
    #=> [22, 11, 33]
    

    These ideas may point you in the right direction.

提交回复
热议问题