65

For Array, there is a pretty sort method to rearrange the sequence of elements. I want to achieve the same results for a String.

For example, I have a string str = "String", I want to sort it alphabetically with one simple method to "ginrSt".

Is there a native way to enable this or should I include mixins from Enumerable?

Pierre-Louis Gottfrois
  • 17,561
  • 8
  • 47
  • 71
steveyang
  • 9,178
  • 8
  • 54
  • 80

5 Answers5

133

The chars method returns an enumeration of the string's characters.

str.chars.sort.join
#=> "Sginrt"

To sort case insensitively:

str.chars.sort(&:casecmp).join
#=> "ginrSt"
Omar Ali
  • 8,467
  • 4
  • 33
  • 58
molf
  • 73,644
  • 13
  • 135
  • 118
15

Also (just for fun)

str = "String"
str.chars.sort_by(&:downcase).join
#=> "ginrSt"
fl00r
  • 82,987
  • 33
  • 217
  • 237
3
str.unpack("c*").sort.pack("c*")
3

You can transform the string into an array to sort:

'string'.split('').sort.join
imtk
  • 1,510
  • 4
  • 18
  • 31
1

If you deal with Unicode text, you might prefer to use String#grapheme_clusters:

"a\u0300e".chars.sort.join
=> "aè" # diacritic moved!
"a\u0300e".grapheme_clusters.sort.join
=> "àe" # expected result
psychoslave
  • 2,783
  • 3
  • 27
  • 44