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?

5 Answers 5

132

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"
1
  • 18
    or str.chars.sort(&:casecmp).join
    – tokland
    Mar 7, 2012 at 12:05
15

Also (just for fun)

str = "String"
str.chars.sort_by(&:downcase).join
#=> "ginrSt"
1
  • I like the sort_by method more, because it is more clear and easy
    – Sam P
    Mar 2, 2021 at 16:32
3

You can transform the string into an array to sort:

'string'.split('').sort.join
2
str.unpack("c*").sort.pack("c*")
1
  • 5
    add some explanation to it. what exactly are you trying to say? May 15, 2013 at 14:52
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.