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!
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With