I had the following code:
def sort_descending _objects, field
_objects.sort { |b,a| a.send(field) <=> b.send(field) }
end
When a.send(field)
returns a String
and b.send(field)
returns an Integer
, then an ArgumentError
is thrown. I tried to catch this exception by:
def sort_descending _objects, field
_objects.sort { |b,a| safe_compare(a,b,field) }
end
def safe_compare a, b, field
a.send(field) <=> b.send(field)
rescue
a.send(field).to_s <=> b.send(field).to_s
end
but this also throws an ArgumentError
. I have no idea why. Can anybody explain this behavior of exceptions thrown by sort?
Though this workaround works, it looks ugly
def sort_ascending _objects, field
_objects.sort do |a,b|
safe_compare(a,field,b) <=> safe_compare(b,field,a)
end
end
def safe_compare a, field, b
_a,_b = a.send(field), b.send(field)
_a.class == _b.class ? _a : _a.to_s
end
Code to reproduce is here.