# Rearranging the letters of a word

**URL:** <https://www.ruby-forum.com/t/rearranging-the-letters-of-a-word/164443>\
**Category:** Rails\
**Created:** [April 1, 2009, 2:45pm UTC](https://www.ruby-forum.com/t/rearranging-the-letters-of-a-word/164443 "2009-04-01T14:45:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [April 1, 2009, 2:45pm UTC](https://www.ruby-forum.com/t/rearranging-the-letters-of-a-word/164443/1 "2009-04-01T14:45:34Z")

</div>

Hello there,

```
 I have to rearrange the letters of a word in all possible ways in

```

my rails application.I am not getting the exact way doing so, please  
can anybody help me in developing that logic.

Thank you in advance.

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [April 1, 2009, 3:35pm UTC](https://www.ruby-forum.com/t/rearranging-the-letters-of-a-word/164443/2 "2009-04-01T15:35:31Z")

</div>

# Based on:

# [http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/139290](http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/139290)

# Author: Endy Tjahjono

class String  
def perm  
return [self] if self.length \< 2  
ret = []

```
   0.upto(self.length - 1) do |n|
      #rest = self.split('')
      rest = self.split(//u) # for UTF-8 encoded

```

strings  
picked = rest.delete\_at(n)  
rest.join.perm.each { |x| ret \<\< picked + x }  
end

```
   ret

```

end  
end

p “abc”.perm #=\> [“abc”, “acb”, “bac”, “bca”, “cab”, “cba”]
