Juliana Peña Juliana Peña - 1 month ago 10
Ruby Question

Check if string is repetition of an unknown substring

I'm trying to write a regex or Ruby method which will find the longest repeated pattern in a string. For example:

"abcabc" => "abc"
"cccc" => "c"
"abcd" => "abcd"


What is the best way to implement this? I naïvely tried
/^(.*)*$/
but that won't work as it just matches the full string.

Answer

I knew it couldn't be that complicated, so I thought it over and found a solution:

def unrepeat(str)
  n = str.size

  newstr = str
  n.times do |i|
     newstr = newstr[-1] + newstr[0..-2]
     if newstr == str
        return i + 1
     end
  end
end

This will return the length of the repeated pattern. It finds this by generating rotations of the string.