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?


source to share

2 answers

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



This works in Ruby 1.8 and 1.9.

You can find Ruby Doc here.



Nice and simple:

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




All Articles