Taking the code from <a title="Permutations in Ruby and Python" href="http://abachman.disqus.com/simple_permutations_in_python_and_ruby/" target="_blank">this other blog</a> … It's pretty elegant Ruby!

I won't waste your time repeating what the guy wrote in his blog - you're welcome to go read it. I just felt that I should help spread a little this elegant implementation of the standard permutation algorithm, fixing a small bug within it in the process. If, like me, you have issues understanding how to use this, well - you have to use this function and call a block of code on it. It runs the block of code on each permutation it finds.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def permutations array
  if array.size < 2
    yield array
  else
    array.each do |element|
      permutations(array.select() {|n| n != element}) \
      {|val| yield([element].concat val)}
    end
  end
end