如何在Ruby中以相反的顺序有效地处理字符串中的行?

rus*_*oue 2 ruby string

我试图找到以相反顺序处理Ruby字符串中的行的最有效方法.这是我的两种方法:

def double_reverse(lines)
    lines.reverse!
    lines.each_line do |line|
        line.chomp!
        line.reverse!
        puts line
    end
end

def split_and_reverse(lines)
    lines.split("\n").reverse.each do |line|
        puts line
    end
end

if __FILE__ == $0
    lines = "This is the first line.\nThis is the second line"
    double_reverse(lines)
    lines = "This is the first line.\nThis is the second line"
    split_and_reverse(lines)
end
Run Code Online (Sandbox Code Playgroud)

我想知道哪一个会使用更少的内存.还有其他方法可以使用更少的资源吗?我主要关心的是内存使用情况,但是如果我可以减少CPU的使用率也会很好.

编辑1:

在我的用例中lines可以有超过一百万行.如果split要将内存使用量增加2倍,那对我来说肯定是个问题.但是,如果Ruby VM足够聪明,可以确定lines在调用split并释放内存之后不会使用它,那么这可能不是问题.另一方面,就地reverse!方法在理论上似乎更有效,因为它可以在不做任何副本的情况下完成lines.

Mat*_*att 6

尝试使用Array#reverse_each:

lines.split("\n").reverse_each do |line|
    puts line
end
Run Code Online (Sandbox Code Playgroud)

或者,如果节省内存是您的首要任务,那么这是一种方法,使用String#rindex哪一个可以相当确定不会在原始字符串之外进行任何额外的重要内存分配:

j = lines.length-1 # lines is the full string, not an array

while -1 <= j
  i = lines.rindex("\n", j) || -1
  line = lines[i+1..j]
  puts line
  j = i-1
end
Run Code Online (Sandbox Code Playgroud)