Tuesday, 20 August 2013

How does the spaceship operator in ruby throws exceptions?

How does the spaceship operator in ruby throws exceptions?

Can anybody explain this strange behavior of exceptions thrown by sort ?
1.) I had the following ruby-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.
So far, so good.
2.) Next I tried to catch this exception as:
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
Shouldn't this work?
But this also throws an ArgumentError. I have no idea why?
Can anybody explain this?
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 at
https://gist.github.com/iboard/6288415#file-ruby_sort_exceptions-rb

No comments:

Post a Comment