Search code examples
ruby-on-railsarraysrubystringdivide-by-zero

How do I apply a division operator on a string in Ruby?


I'm trying to add the division operator / to String, which takes an integer.

The operator should produce an array of strings. The size of the array is the given integer, and its elements are substrings of the original such that, when concatenated in order, produce the original string.

If the string length is not evenly divisible by the integer, some substrings should be (one character) longer than the others. No two strings should differ in length by more than one, and any longer ones should appear before any shorter ones.

Like this:

"This is a relatively long string" / 7
# => ["This ", "is a ", "relat", "ively", " lon", "g st", "ring"]

How can I start?


Solution

  • You could use recursion.

    class String
      def /(n)
        return [self] if n==1
        m = (self.size.to_f/n).ceil
        [self[0...m]].concat(self[m..-1] / (n-1))
      end
    end
    
    str = "This would be a woefully short string had I not padded it out."
    
    str / 7
      # => ["This woul", "d be a wo", "efully sh", "ort strin", "g had I n",
      #     "ot padded", " it out."] 
    
    
    (str / 7).map(&:size)
      #=> [10, 10, 9, 9, 9, 9, 9]