How to duplicate a string N times in Ruby
Overview
We can use the asterisk * operator to duplicate a string for the specified number of times.
The asterisk operator returns a new string that contains a number of copies of the original string.
Syntax
string * int
Parameters
-
string: the string you want to duplicate. -
int: the number of times that you want to duplicate the string.
Return value
The return value is a new string with n copies of the original string.
Code example
In the code below, we use the * operator to duplicate certain strings and print out the return values.
# create stringsstr1 = "Heyyo!"str2 = "Hi!"str3 = "Edpresso"# duplicate the stringsa = str1 * 2 # 2 timesb = str2 * 5 # 4 timesc = str3 * 7 # 7 timesputs aputs bputs c