On 09.01.2009 19:47, pat eyler wrote: > On Fri, Jan 9, 2009 at 11:29 AM, Chris Shea <cmshea / gmail.com> wrote: >> On Jan 9, 11:20 am, Mark Watson <mark.wat... / gmail.com> wrote: >>> I don't usually worry too much about efficiency unless runtime >>> performance becomes an issue so I use a_string.split.join(' ') to >>> remove extra spaces because the code is short and readable. >>> >>> This is certainly inefficient. What is the fastest idiom for this >>> operation? >>> >>> Thanks, >>> Mark >> Haven't benchmarked it, > > > require 'benchmark' > > n = 1_000_000 > > Benchmark.bm(10) do |x| > x.report("gsub") { n.times do > "This is a test string.".gsub(/ +/, ' ') > end > } > x.report("gsub!") { n.times do > "This is a test string.".gsub!(/ +/, ' ') > end > } > x.report("split.join") { n.times do > "This is a test string.".split.join(' ') > end > } > end Note that these behave differently. A more appropriate comparison would be to use /\s+/ as regular expression for gsub!. Interesting figures btw. I would have guessed that gsub! is fastest - live and learn. Kind regards robert -- remember.guy do |as, often| as.you_can - without end