June 2007
Intermediate to advanced
294 pages
8h 6m
English
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.
#!/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
endThis program introduces a concept called recursion, which (like ...
Read now
Unlock full access