C
carp __
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.
The code looks like this:
my_array.sort {
|x,y| x.some_attribute <=> y.some_attribute
}
Naturally, if some_attribute is nil, the comparison failed (since nil is
not comparable). I am looking for something like this:
my_array.sort {
|x,y| x.some_attribute <=> y.some_attribute unless
(x.some_attribute.nil? or y.some_attribute.nil?)
}
which I have tried without having success (Error was: comparison of
MyClass with MyClass failed).
Does anyone know how to do it? Thanks in advance!
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.
The code looks like this:
my_array.sort {
|x,y| x.some_attribute <=> y.some_attribute
}
Naturally, if some_attribute is nil, the comparison failed (since nil is
not comparable). I am looking for something like this:
my_array.sort {
|x,y| x.some_attribute <=> y.some_attribute unless
(x.some_attribute.nil? or y.some_attribute.nil?)
}
which I have tried without having success (Error was: comparison of
MyClass with MyClass failed).
Does anyone know how to do it? Thanks in advance!