Fixnum <=>

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

nainar

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 <=>

Guy Decoux

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 ?

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

AFAIK it's an internal optimization.

    robert

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

see:
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/123637

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

thanks !
nainar

···

On Thu, Nov 24, 2005 at 09:37:25PM +0900, Robert Klemme 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 ?
........

AFAIK it's an internal optimization.

    robert