O'Reilly logo

Ruby by Example by Kevin C. Baird

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

#14 Rotating Characters in a String (rotate.rb)

We’ll close with a simple program that rotates the order of characters within a String. We’ll accomplish this via a method that takes a character (meaning a String of length one) argument. The String to be rotated will try to keep rotating until the character argument appears at index 0. If the character is not found at all, it will return nil.

The Code

  #!/usr/bin/env ruby
  # rotate.rb

  class String

❶   def rotate(char)
❷     return nil unless self.match(char)
❸     return self if (self[0] == char[0])
❹     chars = self.split(//)
      return ([chars.pop] + chars).join('').rotate(char)    Recursion
    end

❻   def rotate!(char)
      replace(rotate(char))
    end

  end

How It Works

This program introduces a concept called recursion, which (like ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required