Problem z najprostszego rozwiązania gsub(/\s+/, ' ')
jest to, że jest bardzo powolny, gdyż zastępuje każdą przestrzeń, nawet jeśli jest to pojedynczy. Ale zwykle jest 1 spacja między słowami i powinniśmy ją naprawić tylko wtedy, gdy są 2 lub więcej białych znaków w sekwencji.
lepszym rozwiązaniem jest gsub(/[\r\n\t]/, ' ').gsub(/ {2,}/, ' ')
- najpierw pozbyć specjalnych whitespaces a następnie wycisnąć przestrzeni normalnych
def method1(s) s.gsub!(/\s+/, ' '); s end
def method2(s) s.gsub!(/[\r\n\t]/, ' '); s.gsub!(/ {2,}/, ' '); s end
Benchmark.bm do |x|
n = 100_000
x.report('method1') { n.times { method1("Lorem ipsum\n\n dolor \t\t\tsit amet, consectetur\n \n\t\n adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } }
x.report('method2') { n.times { method2("Lorem ipsum\n\n dolor \t\t\tsit amet, consectetur\n \n\t\n adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } }
end;1
# user system total real
# method1 4.090000 0.010000 4.100000 ( 4.124844)
# method2 1.590000 0.010000 1.600000 ( 1.611443)
To jest poprawna odpowiedź. I ładne imię, mogę dodać . :) –