i have a text file that consists of these:
player1
10
player2
13
player3
60
These are the player name and score. For example, the score for player 1 is 10 and the score for player 2 is 13 and so on. I want to sort the text file by score. For example:
player3 60
player2 13
player1 10
You need to read the file into an array, do some manipulation, then write back to file. Assuming the source file contains pairs of rows as showed..
First read the lines of the file into an array, File#readlines (note, chomp: true
for stripping "\n"
).
data = File.readlines('score.txt', chomp: true)
#=> ["player1", "10", "player2", "13", "player3", "60"]
Once you have your array, group every two elements(Enumerable#each_slice) and sort by the second element considered as an integer (.to_i
) (Enumerable#sort_by). Note the -
sign for reversing the order of sorting. As last operation map
(Enumerable#map) to join
the pair of elements in the nested array (Array#join):
score_sorted = data.each_slice(2).sort_by { |_, score| -score.to_i}.map{ |ary| ary.join(' ') }
#=> ["player3 60", "player2 13", "player1 10"]
Finally, write the array back to file (File#open):
File.open("score_sorted.txt", "w+") { |f| f.puts score_sorted }