How to sort a string's characters alphabetically?

RubyStringSorting

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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"

Solution 2 - Ruby

Also (just for fun)

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

Solution 3 - Ruby

You can transform the string into an array to sort:

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

Solution 4 - Ruby

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

Solution 5 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsteveyangView Question on Stackoverflow
Solution 1 - RubymolfView Answer on Stackoverflow
Solution 2 - Rubyfl00rView Answer on Stackoverflow
Solution 3 - RubyimtkView Answer on Stackoverflow
Solution 4 - Rubyuser2386335View Answer on Stackoverflow
Solution 5 - RubypsychoslaveView Answer on Stackoverflow