3

Possible Duplicate:
How to sort a string's characters 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?

Community
  • 1
  • 1
Amar
  • 393
  • 1
  • 5
  • 9

2 Answers2

10

Tokland's comment is so nice it deserves to be a full-fledged answer:

str.chars.sort.join

This works in Ruby 1.8 and 1.9.

You can find the Ruby Doc here.

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
3

Nice and simple:

str = 'bacd'
p str.split('').sort.join # => "abcd"
Jakobinsky
  • 1,294
  • 8
  • 11