如何按照ruby中字符串中的数字对多行字符串进行排序

时间:2015-10-09 06:06:18

标签: ruby

我有一个包含多个字符串的txt文件:

John finished the game after 3 rounds in 45 seconds
James finished the game after 3 rounds in 65 seconds
Jane finished the game after 2 rounds in 15 seconds

我如何通过比较首轮数和每位玩家完成游戏以返回重新排列的列表所需的时间来对这些结果进行排序:

Jane finished the game after 2 rounds in 15 seconds
John finished the game after 3 rounds in 45 seconds
James finished the game after 3 rounds in 65 seconds

我尝试过使用

lead_arr = [] 
File.open("game_results.txt", "r+") do | line | 
  line.each_line do |text| 
    lead_arr << text.split
  end
end
leader = lead_arr.sort_by(lead_arr[7].to_i)

3 个答案:

答案 0 :(得分:4)

您可以将sort_byscanto_i结合使用:

strings = [
  'John finished the game after 3 rounds in 45 seconds',
  'James finished the game after 3 rounds in 65 seconds',
  'Jane finished the game after 2 rounds in 15 seconds'
]

strings.sort_by { |string| string.scan(/\d+/).map(&:to_i) }
#=> ["Jane finished the game after 2 rounds in 15 seconds",
#    "John finished the game after 3 rounds in 45 seconds",
#    "James finished the game after 3 rounds in 65 seconds"]

答案 1 :(得分:3)

我更喜欢更多的OO-ish方法。它不是那么简洁,但我认为它更有意图揭示并且更容易修改。

class Result
  def initialize(line)
    @line = line
  end

  def <=>(other)
    score <=> other.score
  end

  def score
    [rounds, seconds]
  end

  def rounds
    @line[/\d+ rounds/].to_i
  end

  def seconds
    @line[/\d+ seconds/].to_i
  end
end

File.open("game_results.txt")
 .each_line
 .sort_by { |line| Result.new(line) }

答案 2 :(得分:0)

以下是我使用的代码。

lead_arr = []
  File.open("game_results.txt", "r") do | lines |
  lines.each_line do |text|
  lead_arr << text
  @leader = lead_arr.sort_by { |line| line[/\d+ rounds/].to_i &&  line[/\d+ seconds/].to_i}