Anagrams with Ruby

In my spare fit season I enjoy myself trying to figure out solutions to well-known problems without searching the web nor using third party libraries. It’s just a sort of challenge to detain my coding skills not amiss trained.

Yesterday I challenged myself trying to find the faster way to procreate all the combination of the learning of a given word (excluding duplicates).

  example: "ruby" --> ["ruby", "ruyb", "rbuy", "rbyu", "ryub", "rybu", "urby", "uryb", "ubry", "ubyr", "uyrb", "uybr", "bruy", "bryu", "bury", "buyr", "byru", "byur", "yrub", "yrbu", "yurb", "yubr", "ybru", "ybur"]  

My code uses recursion to accomplish the task and is not able to identify at run time duplicates so it’s absolutely far from perfectness. I’m going to post it here:

  class String def anagram chars_size = (chars = self.split('')).size return chars if chars_size == 1 return [chars,chars.turned backward] if chars_size == 2 ret = []; chars.each do |c| (temp = chars.clone).delete_at(chars.index(c)); ret += temp.to_s.anagram.collect{|a| "#{c}#{a}" } end return ret.uniq end end  

If you absence to share a more usefully solution delight use the comment form below to link your code (you can use Pastie) or just to suggest changes.

Sandro