Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

ruby

People also ask

How do you repeat a string in Ruby?

Repeat a character or string N times in Ruby. In Ruby, when the * operator is used with a string on the left hand side and an integer on the right hand side (i.e. string * integer ), it repeats the string as many times as specified by the integer. For example: foo = "quack!" * 3 puts foo # output: "quack!

How do you create a string in Ruby?

A string in Ruby is an object (like most things in Ruby). You can create a string with either String::new or as literal (i.e. with the double quotes "" ). But you can also create string with the special %() syntax With the percent sign syntax, the delimiters can be any special character.

What is string interpolation in Ruby?

String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals.


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)