defining sort <=> for a class

A

Adam Akhtar

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???
 
T

Thomas Wieczorek

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]
 
A

Adam Akhtar

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.
 
P

Phlip

Adam said:
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
 
A

Adam Akhtar

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top