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

前端 未结 2 1542
别那么骄傲
别那么骄傲 2021-01-31 12:59

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\"}


        
相关标签:
2条回答
  • 2021-01-31 13:32

    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)
    
    0 讨论(0)
  • 2021-01-31 13:47
    str = "0" * 999999
    
    0 讨论(0)
提交回复
热议问题