I may be missing something obvious . Why is the ‘<=>’ operator not
called when there is no block supplied to sort ?.The Pickaxe book
says ( apropos Array.sort ):
" Comparisons for the sort will be done using the <=> operoator OR
using an optional code block"
How is the comparison done in the second case ?
class Fixnum
alias oldcmp <=>
def <=>(other)
puts " <=> called with #{self} and #{other} "
oldcmp(other)
end
end
p [9,1,7,3,5].sort { |a, b| a <=> b}
p [99,11,77,33,55].sort
v> How is the comparison done in the second case ?
ruby has some optimizations : if the 2 elements that it need to compare
are both Fixnum, or both Strings it make internally the comparison and
don’t call <=>
On Thu, Nov 24, 2005 at 09:37:25PM +0900, Robert K. wrote:
v.nainar wrote:
I may be missing something obvious . Why is the ‘<=>’ operator not
called when there is no block supplied to sort ?.The Pickaxe book
says ( apropos Array.sort ):
" Comparisons for the sort will be done using the <=> operoator OR
using an optional code block"
How is the comparison done in the second case ?
…
there are optimisations in the core classes such as String which also
currently affect user-defined subclasses. you can make sure that your
own own <=> operator is called by using:
something.sort { | i, j | i <=> j }
instead of
something.sort
alex
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.