'How to sort a string's characters alphabetically?

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?



Solution 1:[1]

Also (just for fun)

str = "String"
str.chars.sort_by(&:downcase).join
#=> "ginrSt"

Solution 2:[2]

You can transform the string into an array to sort:

'string'.split('').sort.join

Solution 3:[3]

str.unpack("c*").sort.pack("c*")

Solution 4:[4]

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

"a\u0300e".chars.sort.join
=> "ae?" # diacritic moved!
"a\u0300e".grapheme_clusters.sort.join
=> "a?e" # expected result

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fl00r
Solution 2 imtk
Solution 3 user2386335
Solution 4 psychoslave