Skip to content

Instantly share code, notes, and snippets.

@iboard
Last active January 20, 2019 07:59
Show Gist options
  • Save iboard/6288415 to your computer and use it in GitHub Desktop.
Save iboard/6288415 to your computer and use it in GitHub Desktop.
Stackoverflow-example
require 'ostruct'
# ad 1)
def sort_descending1 _objects, field
_objects.sort { |b,a| a.send(field) <=> b.send(field) }
end
# ad 2)
def safe_compare2 a,b,field
a.send(field) <=> b.send(field)
rescue => e
puts "swallow #{e}"
end
def sort_descending2 _objects, field
_objects.sort { |b,a| safe_compare2(a,b,field) }
end
# ad 3)
def safe_compare3 a,field,b
_a,_b = a.send(field), b.send(field)
_a.class == _b.class ? _a : _a.to_s
end
def sort_descending3 _objects, field
_objects.sort do |b,a|
safe_compare3(a,field,b) <=> safe_compare3(b,field,a)
end
end
# MAIN
objects = [
OpenStruct.new( foo: 0 ),
OpenStruct.new( foo: 1 ),
OpenStruct.new( foo: 'bar' ),
]
puts "1.) The first attempt"
begin
puts sort_descending1(objects, :foo).inspect
rescue => e
puts e.inspect
end
puts "\n2.) Try to catch the error"
begin
puts sort_descending2(objects, :foo).inspect
rescue => e
puts e.inspect
end
puts "\n3.) Workaround"
begin
puts sort_descending3(objects, :foo).inspect
rescue => e
puts "NEVER REACHED " + e.inspect
end
# OUTPUT
#
# 1.) The first attempt
# #<ArgumentError: comparison of OpenStruct with OpenStruct failed>
#
# 2.) Try to catch the error
# #<ArgumentError: comparison of OpenStruct with OpenStruct failed>
#
# 3.) Workaround
# [#<OpenStruct foo="bar">, #<OpenStruct foo=1>, #<OpenStruct foo=0>]
#
#
# Best solution posted by [@7stud](http://stackoverflow.com/users/926143/7stud) at stackoverflow
#
puts "\n4.) A clean solution"
def safe_compare a, b, field
result = a.send(field) <=> b.send(field)
result ||= a.send(field).to_s <=> b.send(field).to_s
end
puts objects.sort { |a,b| safe_compare a,b,:foo }
@iboard
Copy link
Author

iboard commented Aug 20, 2013

Note: Line 12, this rescue is not reached.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment