I have an array of objects that I need to sort by a position attribute that could be an integer or nil, and I need the objects that have the nil position to be at the end of
You can do this without overriding the spaceship operator by defining a new comparison method.
class Child
include Comparable
def compare_by_category(other)
return 0 if !category && !other.category
return 1 if !category
return -1 if !other.category
category.position <=> other.category.position
end
end
The sort
method can take a block, so you can then sort using this new method:
children.sort {|a,b| a.compare_by_category(b) }