title: Find all the possible permutations using Ruby and recursion
body: <p>I've been trying to solve a simple quiz question to find all the possible permutation of a string using Ruby and recursion.</p>
  
  <p>I have the following Ruby code:</p>
  
  <pre><code>def permutation(string)
    return [string] if string.size &lt; 2
  
    chr    = string.chars.first
    perms  = permutation(string[1..-1])
  
    result = []
  
    for perm in perms
      for i in (0..perm.size)
        result &lt;&lt; (perm[0..i] + chr + perm[i..-1])
      end
    end
  
    return result  
  end
  </code></pre>
  
  <p>Whenever I try to test the code with <strong>puts permutation("abc")</strong> I get the following output:</p>
  
  <pre><code>cacbc
  cbabc
  cbcac
  cbca
  cacb
  cbab
  cba
  </code></pre>
  
  <p>Theoretically speaking it's supposed to be a very simple and straightforward problem, but I'm sure I'm doing something wrong. Most probably it's something with the ranges of the loops. And I know that Ruby Array class has instance method <em>permutation</em> to do that but I'm trying to solve it for practising. </p>
  
  <p>Please note that the complexity is O(N!) for the current implementation. Is there anyway to enhance the performance further? </p>