Reputation: 43
I know this is a simple problem, but for some reason it wont click. I want to repeat characters in a string for a fixed amount. For example:
str = 'abcde'
temp = ''
x = 8
for i in 0..x
if str[i].nil?
temp << ''
else
temp << str[i]
end
end
Except I get no input. What I need is:
abcdeabc
Please, any help would be appreciated. If there is a better working way to do this instead of my not working naive approach, I would like to know
Upvotes: 1
Views: 1205
Reputation: 61510
You can easily do this using slicing
def repeat_x_chars(str, x)
# special cases
return str if x == 0
return "" if str.length == 0
return str + str[0..(str.length % x)] # slicing
end
Upvotes: 1
Reputation: 65477
Using ljust
should do it:
str = 'abcde'
str.ljust(8, str)
# => "abcdeabc"
str.ljust(12, str)
# => "abcdeabcdeab"
Upvotes: 5
Reputation: 35803
Try this one-liner:
res = (str * (x / str.length)) + str[0...(x%str.length)]
Upvotes: 0
Reputation: 179452
If you want to repeat a string a few times, use *
. We can combine that with slicing to get this solution:
def repfill(str, n)
nrep = (Float(n) / str.length).ceil
return (str * nrep)[0...n]
end
Example:
irb(main):030:0> repfill('abcde', 8)
=> "abcdeabc"
As for your solution, what you are missing is a modulo to repeat the string from the beginning:
str = 'abcde'
temp = ''
x = 8
for i in 0...x # note ... to exclude last element of range
temp << str[i % str.length]
end
Upvotes: 3