How to sort a string in ruby?

Possible duplicate:
How to sort the characters in a string alphabetically?

Assuming there is a simple string str = "bacd" I want to sort it so that the result contains result = "abcd"

How do I do this in Ruby?

+3


source to share


2 answers


Tokland's comment is so good that it deserves a full blown answer:

str.chars.sort.join

      



This works in Ruby 1.8 and 1.9.

You can find Ruby Doc here.

+9


source


Nice and simple:



str = 'bacd'
p str.split('').sort.join # => "abcd"

      

+3


source







All Articles