How to sort string characters in alphabetical order?

For an array, there is a nice sort method to change 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 my own way to enable this, or should I include mixins from Enumerable ?

+51
string sorting ruby
Feb 27 '12 at 11:16
source share
4 answers

The chars method returns the numbering of string characters.

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

To sort case insensitively:

 str.chars.sort(&:casecmp).join #=> "ginrSt" 
+115
Feb 27 '12 at 11:20
source share

Also (just for fun)

 str = "String" str.chars.sort_by(&:downcase).join #=> "ginrSt" 
+13
Mar 07 '12 at 16:20
source share
 str.unpack("c*").sort.pack("c*") 
+2
May 15 '13 at 14:33
source share

You can convert a string to an array for sorting:

 'string'.split('').sort.join 
+1
Mar 01 '15 at 4:14
source share



All Articles