How to sort a string's characters alphabetically?
RubyStringSortingRuby 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