Reputation: 85
I am trying to create a program where the first three characters of a string is repeated a given number of times like this:
foo('Chocolate', 3) # => 'ChoChoCho'
foo('Abc', 3) # => 'AbcAbcAbc'
I know I can use length
to count characters, but how do I specify the length of the string to be outputted? Also how can I specify the number of times?
Upvotes: 1
Views: 84
Reputation: 61540
You can use something like this.
def print_first_three_x_times(string, x)
#remove everything but the first three chars
string.slice!(3..string.length)
#print x times
x.times{ print string }
end
output:
Hunter@Hunter-PC ~
$ irb
irb(main):008:0> print_first_three_x_times("Hunter",5)
HunHunHunHunHun=> 5
irb(main):009:0>
Upvotes: 1