Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a string in ruby? [duplicate]

Tags:

ruby

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?

like image 883
Amar Avatar asked Apr 27 '26 10:04

Amar


2 Answers

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.

like image 151
Mark Thomas Avatar answered Apr 28 '26 23:04

Mark Thomas


Nice and simple:

str = 'bacd'
p str.split('').sort.join # => "abcd"
like image 29
Jakobinsky Avatar answered Apr 28 '26 23:04

Jakobinsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!