Juliana Peña Juliana Peña - 1 year ago 83
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 Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download