Hi --

On Mon, 28 Mar 2005 bertrandmuscle / yahoo.com wrote:

> Florian Frank wrote:
>> Daniel Amelang wrote:
>> 
>>> Gotcha. Well, I can tell you firsthand about the controversies of the
>>> 'bang' methods (like 'sort!', etc). Since they really aren't a
>>> necessity (you can get along with just the non-bang versions) and ruby
>>> has only relatively recently acquired sort_by, I bet they just didn't
>>> get around to writing the bang version of sort_by.
>>> 
>> sort! sorts an array in place, while sort always makes a copy from the 
>> original array. This distinction wouldn't be sensible for sort_by, because 
>> it's actually a Schwartzian Transform, that always creates temporary 
>> arrays:
>> 
>> class Array
>>  def sort_by
>>    map { |x| [ x, yield(x) ] }.sort { |a,b|
>>      a.last <=> b.last
>>    }.map { |p| p.first }
>>  end
>> end
>> 
>> The transform makes a lot of sense if the yielded computations is very 
>> expensive, because O(n) < O(n*log(n)). It's good to know about the trade 
>> off between creating temporary arrays and the computation of the sort keys, 
>> if one has to choose between sort(!) and sort_by.
>> 
>
> this is very interesting, thank you.
>
> but for myself and perhaps many other users it comes down to how intuitive 
> the language is. from this perspective: if sort! works, sort_by! should also.

You can always define your own:

   class Array
     def sort_by!(&b)
       replace(sort_by &b)
     end
   end

with the usual caveats about reopening core classes.

> one of the things that drew me to ruby recently was this philosophy, but 
> there have been some off-putting inconsistencies.

Don't be put off.  There are forums for bringing these things to the
attention of Matz and discussing them with him and others, and for
requesting changes to the language if you conclude that that's
appropriate.


David

-- 
David A. Black
dblack / wobblini.net