Menu
Coddy logo textTech

Pattern Finder

Part of the Fundamentals section of Coddy's Ruby journey — lesson 87 of 88.

challenge icon

Challenge

Easy

Read a string from input and find the smallest repeating pattern that forms the entire string.

A valid pattern must:

  • Have a length that divides evenly into the string's total length
  • When repeated the appropriate number of times, recreate the original string exactly

If the string is made of a repeating pattern, print that smallest pattern. If no repeating pattern exists, print the original string.

To check if a pattern works, you can use string multiplication: pattern * count creates a new string by repeating the pattern.

For example, if the input is abcabcabc, the output should be:

abc

If the input is xyxyxyxy, the output should be:

xy

If the input is aaaa, the output should be:

a

If the input is hello, the output should be:

hello

If the input is abcdef, the output should be:

abcdef

Try it yourself

# Read the input string
s = gets.chomp

# TODO: Write your code below
# Find the smallest repeating pattern that forms the entire string
# Hint: Check pattern lengths that divide evenly into the string length
# Use string multiplication (pattern * count) to verify if a pattern works

result = s  # Replace this with your solution

# Output the result
puts result

All lessons in Fundamentals