I want to sort an array of objects of the same class (MyClass). The
array should be sorted by arbitrary attributes of that class, but the
problem is that one attribute can be nil.
class MyClass
def <=>(other)
if @some_attribute.nil?
return -1
elsif @other.some_attribute.nil?
return 1
else @some_attribute <=> other.some_attribute
end
end
end
Farrel
···
On 08/03/07, carp __ <carp@hacksocke.de> wrote:
Hello Rubyists,
I want to sort an array of objects of the same class (MyClass). The
array should be sorted by arbitrary attributes of that class, but the
problem is that one attribute can be nil.
I find your style of mixing imperative and functional return
parameters odd. I would have expected either:
if foo
-1
elsif bar
1
else
x <=> y
end
OR
if foo
return -1
elsif bar
return 1
else
return x <=> y
end
but not the combination you have above. FWIW, I favor the former
style, as it's just a hair faster.
···
On Mar 8, 5:52 am, "Farrel Lifson" <farrel.lif...@gmail.com> wrote:
Define <=> on your class:
class MyClass
def <=>(other)
if @some_attribute.nil?
return -1
elsif @other.some_attribute.nil?
return 1
else @some_attribute <=> other.some_attribute
end
end
end