Repeat method to give "string" "x" number of times
I am trying to write a method that will take two arguments, one for the string and the other for the number of repetitions. here is the code I have:
def repeat(text,c=2)
c.times do print text end
end
repeat ("hi")
the problem is here, I want the result to be "hello hello", I tried "puts" but starts a new line ... [print text "+" text] also doesn't work ...
thanks for the help!
source to share
Your question is unclear. If all you need is to print the text repeated n times, useString#*
def repeat(text, n=2)
print text * n
end
Your example shows what you want to "hi hi"
imply that you would like spaces between each repetition. The shortest way to do this is to useArray#*
def repeat(text, n=2)
print [text] * n * ' '
end
source to share
Enumerator#cycle
returns a counter:
puts ['hi'].cycle(3).to_a.join(' ')
# => hi hi hi
Breaking code:
['hi']
creates an array containing a string
cycle(3)
creates an enumerator from an array that repeats the elements 3 times
.to_a
creates an array from the enumerator so that the method join
Array
can produce the final line of output.
source to share
I see no point in creating an array (with or without collect ()) and then calling join (). This works too:
def repeat(text, c=2)
c.times { |i| print text; print ' ' unless i+1 == c }
end
While this is a bit more verbose (which may not be ruby), it does less work (which perhaps makes more sense).
source to share