Home > katas > String repeat (8kyu) [Ruby]

String repeat (8kyu) [Ruby]


Chek kata on Codewars

Description:

Write a function called repeat_str which repeats the given string src exactly count times.

repeatStr(6, "I") // "IIIIII"
repeatStr(5, "Hello") // "HelloHelloHelloHelloHello"

Solution 1.1

Let's start with a loop solution.

def repeat_str (n, s)
    newString = ''
    n.times do |i|
        newString += s
    end
    newString
end

Solution 1.2

def repeat_str (n, s)
    newString = ''
    for i in 1..n
        newString += s
    end
    newString
end

Solution 1.3

We can add an array to this loop.

def repeat_str (n, s)
  array = []
  n.times do |i|
    array.push(s)
  end
  array.join
end

Solution 1.3 +

def repeat_str (n, s)
  array = []
  n.times do |i|
    array << s
  end
  array.join
end

Solution 2.1

def repeat_str (n, s)
  s * n
end

Solution 3.1

Let's solve it recursively.

def repeat_str (n, s)
    n > 1 ? s + repeat_str(n - 1, s) : s
end

Solution 4.1

def repeat_str (n, s)
    Array.new(n+1).join(s)
end
© 2021, Andrew Losseff