How to Repeat a String in Ruby Without Using a Loop?

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!quack!quack!"

If you want to, for example add spaces between each repeated word, then you can do so in the following way:

arr = ["quack!"] * 3
str = arr * " "

puts str # output: "quack! quack! quack!"

You can shorten this into a one-liner like so:

foo = ["quack!"] * 3 * " "

puts foo # output: "quack! quack! quack!"

In the first part (i.e. array * integer), the array containing the word "quack!" is repeated three times (as specified by the integer after the * operator):

["quack!"] * 3 # output: [ "quack!", "quack!", "quack!" ]

Once that operation is complete, in the second part (i.e. array * string) all the array elements are joined into a single string, separated by the value that's specified within the string to the right of the * operator:

["quack!", "quack!", "quack!"] * " " # output: "quack! quack! quack!"

array * string is a shorthand for using array.join(string). You can write the same code using array.join() like so:

arr = ["quack!"] * 3
str = arr.join(" ")

puts str # output: "quack! quack! quack!"

Hope you found this post useful. It was published . Please show your love and support by sharing this post.