Reputation: 11
How can I create a new string which is n copies of a given string in ruby? I tried these but none of them worked -
n = 5
string = "This is a string"
my_string = ""
my_string = n.times do
my_string << string
end
puts my_string
Thanks in advance
Upvotes: 0
Views: 615
Reputation: 68
I don't know if this is exactly what you are looking for. But you can use the string * integer method.
n = 5
string = "This is a string"
my_string = string * n
puts my_string
Upvotes: 0
Reputation: 84373
You can use the String#* method. For example:
str = "This is a string.\n"
str * 5
#=> "This is a string.\nThis is a string.\nThis is a string.\nThis is a string.\nThis is a string.\n"
Similarly, puts str * 5
will return nil, but print the output with newlines to standard output. For example:
This is a string. This is a string. This is a string. This is a string. This is a string.
Upvotes: 1
Reputation: 20796
Use the String#* operator:
n = 5
string = "This is a string"
my_string = string * n
This is a stringThis is a stringThis is a stringThis is a stringThis is a string
Upvotes: 1
Reputation: 33430
You can create an array with n
string
elements, and then join each of them:
Array.new(n, string).join
# "This is a stringThis is a stringThis is a stringThis is a stringThis is a string"
You can also use the *
method which returns a new String containing integer copies of self:
string * n
# "This is a stringThis is a stringThis is a stringThis is a stringThis is a string"
Upvotes: 3