From: John Joyce Date: 2007-11-01T16:11:34+09:00 Subject: Re: Sorting a string... On Oct 31, 2007, at 6:46 PM, Konrad Meyer wrote: > Quoth Joel VanderWerf: >> David A. Black wrote: >>> Hi -- >>> >>> On Thu, 1 Nov 2007, Daniel Waite wrote: >>> >>>> I was porting a small Python script over to Ruby and realized >>>> Ruby does >>>> not sort strings as I expected it would. >>>> >>>> 'cba'.sort # ["cba"] >>>> >>>> So I wrote this... >>>> >>>> class String >>>> >>>> def sort >>>> bytes = Array.new >>>> self.each_byte { |byte| bytes << byte } >>>> bytes.sort.collect { |byte| byte.chr }.join >>>> end >>>> >>>> end >>>> >>>> 'cba'.sort # "abc" >>> >>> I wouldn't overwrite a core method like that; you could end up with >>> some very unexpected results. It's better to give it a different >>> name. >> >> Also, note that String#sort depends on String#to_a being defined, >> which >> is no longer true in 1.9. It's kind of an accident that "cba".sort >> works >> at all. >> >> I guess that means someone will be free to implement String#sort, as >> long as they stick to 1.9. Maybe there will be a core implementation >> that works as expected? >> >> -- >> vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407 > > Well, anyone who's sorting a string really just wants to sort the > component > letters, so my_str.split('').sort.join('') is the way to go. If > they want to > add a method to String to simplify this, they can do that. > > -- > Konrad Meyer http://konrad.sobertillnoon.com/ Presuming an English alphabetic order, perhaps yes. What about case-sensitivity? What about other languages? Ordering always depends on little details. A basic English alphabetic ordering might be an overly simple use-case. Although, it is a great example of a Ruby one-liner. Remember unicode support is coming (we hope) to Ruby 2, and 1.9 is really an unfinished 2.