@azlisum: 你们不会因为你们的混淆而stor。 使用:
output = string.lines.map{|line|change_line(line)}.join
比较四条按行程处理的方法:
# Inject method (proposed by @steenslang)
output = string.each_line.inject(""){|s, line| s << change_line(line)}
# Join method (proposed by @Lars Haugseth)
output = string.lines.map{|line|change_line(line)}.join
# REGEX method (proposed by @olistik)
output = string.gsub!(/^(.*)$/) {|line| change_line(line)}
# String concatenation += method (proposed by @Erik Hinton)
output = ""
string.each_line{|line| output += change_line(line)}
基准时间:
user system total real
Inject Time: 7.920000 0.010000 7.930000 ( 7.920128)
Join Time: 7.150000 0.010000 7.160000 ( 7.155957)
REGEX Time: 11.660000 0.010000 11.670000 ( 11.661059)
+= Time: 7.080000 0.010000 7.090000 ( 7.076423)
@steenslag指出,s +=a href=“https://stackoverflow.com/questions/5686621/ruby-string-concatenation-and>new string for each concatenation,而且通常没有最佳选择。
So given that, and given the times, your best bet is:
output = string.lines.map{|line|change_line(line)}.join
此外,这也是一种更清洁的眼光选择。
Notes:
Using Benchmark
Ruby-Doc: Benchmark