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.

-- 
Florian Frank