nizbit
nizbit

Reputation: 43

Repeat characters in a string

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

Answers (5)

analog str_repeat

"abcde" * 3   
#-> "abcdeabcdeabcde"

Upvotes: 1

Hunter McMillen
Hunter McMillen

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

Zabba
Zabba

Reputation: 65477

Using ljust should do it:

str = 'abcde'

str.ljust(8, str)
# => "abcdeabc" 

str.ljust(12, str)
# => "abcdeabcdeab" 

Upvotes: 5

Linuxios
Linuxios

Reputation: 35803

Try this one-liner:

res = (str * (x / str.length)) + str[0...(x%str.length)]

Upvotes: 0

nneonneo
nneonneo

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

Related Questions