I was recently working through a series of coding puzzles, and came across one that asks you to write a function that takes a string and produces every possible permutation of its letters. So “abc” could be “abc”, “acb”, “bac”, “bca”, “cab”, “cba”. The book where I found the puzzle had an example of how to solve the problem in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
I was halfway through working through the problem in Ruby, when it occurred to me that Ruby might have an easier way of doing things. It does. It has a permutate method that allows us to solve the problem with one line of code. Behold:
1
|
|