In Ruby how do I generate a long string of repeated text?

What is the best way to generate a long string quickly in ruby? This works, but is very slow:

str = ""
length = 100000
(1..length).each {|i| str += "0"}

I've also noticed that creating a string of a decent length and then appending that to an existing string up to the desired length works much faster:

str = ""
incrementor = ""
length = 100000
(1..1000).each {|i| incrementor += "0"}
(1..100).each {|i| str += incrementor}

Any other suggestions?


str = "0" * 999999

Another relatively quick option is

str = '%0999999d' % 0

Though benchmarking

require 'benchmark'
Benchmark.bm(9)  do |x|
  x.report('format  :') { '%099999999d' % 0 }
  x.report('multiply:') { '0' * 99999999 }
end

Shows that multiplication is still faster

               user     system      total        real
format  :  0.300000   0.080000   0.380000 (  0.405345)
multiply:  0.080000   0.080000   0.160000 (  0.172504)