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

RubyString

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

str = "0" * 999999

Solution 2 - Ruby

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarkus OrrellyView Question on Stackoverflow
Solution 1 - RubyFMcView Answer on Stackoverflow
Solution 2 - RubyrampionView Answer on Stackoverflow