I'm trying to write a method that will take two arguments, one for the string, and the other the number of times it will be repeated. here is the code of i have:
def repeat(text,c=2)
c.times do print text end
end
repeat ("hi")
problem here is, I want to have the result to be "hi hi" i tried "puts" but that starts a new line... [ print text " + " text ] doesn't work as well...
thanks for the help!
The repeat() method returns a string that has been repeated a desired number of times. If the count parameter is not provided or is a value of 0, the repeat() method will return an empty string. If the count parameter is a negative value, the repeat() method will return RangeError.
The string can be repeated N number of times, and we can generate a new string that has repetitions. repeat() method is used to return String whose value is the concatenation of given String repeated count times. If the string is empty or the count is zero then the empty string is returned.
To repeat a string in Python, We use the asterisk operator ” * ” The asterisk. is used to repeat a string n (number) of times. Which is given by the integer value ” n ” and creates a new string value.
repeat() The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
Your question is unclear. If all you want is to print the text repeated n times, use String#*
def repeat(text, n=2)
print text * n
end
Your example result says you want "hi hi"
implying you would like spaces between each repetition. The most concise way to accomplish that is to use Array#*
def repeat(text, n=2)
print [text] * n * ' '
end
Simply multiply the string by the number, Ruby is smart enough to know what you mean ;)
pry(main)> "abcabcabc" * 3
=> "abcabcabcabcabcabcabcabcabc"
Or you could do something like:
def repeat(text, c=2)
print c.times.collect { text }.join(' ')
end
Enumerator#cycle
returns an enumerator:
puts ['hi'].cycle(3).to_a.join(' ')
# => hi hi hi
Breaking down the code:
['hi']
creates an array containing a string
cycle(3)
creates an enumerator from the array that repeats the elements 3 times
.to_a
creates an array from the enumerator so that the join
method of Array
can create the final output string.
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