Defining sort <=> for a class

If i have a class

class Example

attr_accessor :value

def initialize
    @value = 0
end

end

and I have an array of examples and want to sort them based on value how
do i define a <=> for my class. I know its possible as it was a side
comment on an earlier post. Seeing as this is a totally different
subject to that post i decided to ask in a new post - it will be easier
for others who may have the same questoin to search for.

i tried this

class Example

attr_accessor :value

def initialize
    @value = 0
end

def <=>(other_example)
   @value <=> other_example
end
end

but i keep getting an error of undefined method for nill class when i
try to call it like this with an array of example objects

ojects.sort do |one, another|
   one.<=>(another)
end

i also tried
ojects.sort do |one, another|
   one <=>(another)
end

(i.e no period between one and <=>)

where am i going wrong???

···

--
Posted via http://www.ruby-forum.com/.

Heya!

i tried this

class Example

attr_accessor :value

def initialize
   @value = 0
end

Here's the error:

def <=>(other_example)
  @value <=> other_example
end

You want to sort by the value, so you have to compare the values:

def <=>(other_example)
  @value <=> other_example.value
end

A simple example:
a = Example.new
b = Example.new
a.value = 10
arr = [a,b]
# => [#<Example:0x2b5d6a8 @value=10>, #<Example:0x2b5b7cc @value=0>]
arr.sort!
# => [#<Example:0x2b5b7cc @value=0>, #<Example:0x2b5d6a8 @value=10>],
means arr = [b, a]

···

On Sun, Aug 24, 2008 at 2:03 PM, Adam Akhtar <adamtemporary@gmail.com> wrote:

ahh so the <=> thing is called implicitly, i dont have to call it
automatically in my code. I just do sort!.

thanks very much, ill go away and fix it.

···

--
Posted via http://www.ruby-forum.com/.

ahh so the <=> thing is called implicitly, i dont have to call it
automatically in my code. I just do sort!.

Yeah, it is. Enumerable#sort calls implicitly the <=> method of the elements.

thanks very much, ill go away and fix it.

You're very welcome

···

On Sun, Aug 24, 2008 at 3:53 PM, Adam Akhtar <adamtemporary@gmail.com> wrote:

Adam Akhtar wrote:

ahh so the <=> thing is called implicitly, i dont have to call it
automatically in my code. I just do sort!.

Alternately, use sort_by to repurpose the implicit <=>. Examples:

   .sort_by{rand} # a shuffle
   .sort_by{|x| -x } # reverse order
   .sort_by{|r| r.name.downcase } # ascibetic order by name

···

--
   Phlip

  .sort_by{|r| r.name.downcase } # ascibetic order by name

Actually, sorting by a downcase is not strictly an asciibetic sort. It's a cheap form of "collation", where an expensive collation uses your locale to decipher its dictionary order rules. Example: Packing McDonalds in with MacDonalds...

yes ive seen sort_by a few times now. ill start using that in my code.
thanks everyone again.

···

--
Posted via http://www.ruby-forum.com/.