I have a string:
\"foo (2 spaces) bar (3 spaces) baaar (6 spaces) fooo\"
How do I remove repetitious spaces in it so there shou
Which method performs better?
$ ruby -v
ruby 1.9.2p0 (2010-08-18 revision 29036) [i686-linux]
$ cat squeeze.rb
require 'benchmark'
include Benchmark
string = "foo bar bar baaar"
n = 1_000_000
bm(6) do |x|
x.report("gsub ") { n.times { string.gsub(/\s+/, " ") } }
x.report("squeeze ") { n.times { string.squeeze } }
x.report("split/join") { n.times { string.split.join(" ") } }
end
$ ruby squeeze.rb
user system total real
gsub 4.970000 0.020000 4.990000 ( 5.624229)
squeeze 0.600000 0.000000 0.600000 ( 0.677733)
split/join 2.950000 0.020000 2.970000 ( 3.243022)