How to sort a string's characters alphabetically?
Solution 1
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
Also (just for fun)
str = "String"
str.chars.sort_by(&:downcase).join
#=> "ginrSt"
Solution 3
You can transform the string into an array to sort:
'string'.split('').sort.join
Solution 4
str.unpack("c*").sort.pack("c*")
steveyang
After my passion for creation, I learned programming-stuff myself since the year of 2011 and now I am comfortable with html5,css3 and javaScript. I also love the simply design of linux and cleanliness of python and ruby. I am working as the leading UI designer and frontend developer at ELE.ME
Updated on July 05, 2022Comments
-
steveyang almost 2 years
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
?