Created
July 24, 2021 20:00
-
-
Save dandelarosa/3359605e90115e5dc17d483855ec03ce to your computer and use it in GitHub Desktop.
Demonstrate opaque errors when sorting objects in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Player | |
attr_accessor :name, :avg, :hr, :rbi | |
def initialize(name, avg, hr, rbi) | |
@name = name | |
@avg = avg | |
@hr = hr | |
@rbi = rbi | |
end | |
end | |
players = [ | |
Player.new('Dominic Smith', 0.253, 11, 43), | |
Player.new('Brandon Nimmo', 0.299, 2, 14), | |
Player.new('Michael Conforto', 0.203, 6, 24) | |
] | |
puts 'Players before sort' | |
pp players | |
# When the data comes in as expected, both `sort` and `sort_by` execute without errors | |
puts 'Players sorted using sort' | |
pp players.sort { |first_player, second_player| first_player.avg <=> second_player.avg } | |
puts 'Players sorted using sort_by' | |
pp players.sort_by { |player| player.avg } | |
puts 'Call sort_by to sort by multiple fields' | |
pp players.sort_by { |player| [player.avg, player.hr] } | |
# Issues arise when there's missing data | |
players = [ | |
Player.new('Dominic Smith', 0.253, 11, 43), | |
Player.new('Brandon Nimmo', 0.299, 2, 14), | |
Player.new('Michael Conforto', nil, 6, 24) | |
] | |
# puts 'Players sorted using sort' | |
# pp players.sort { |first_player, second_player| first_player.avg <=> second_player.avg } | |
# Traceback (most recent call last): | |
# 1: from mets_sort.rb:37:in `<main>' | |
# mets_sort.rb:37:in `sort': comparison of Player with Player failed (ArgumentError) | |
# puts 'Players sorted using sort_by' | |
# pp players.sort_by { |player| player.avg } | |
# Traceback (most recent call last): | |
# 1: from mets_sort.rb:43:in `<main>' | |
# mets_sort.rb:43:in `sort_by': comparison of Float with nil failed (ArgumentError) | |
# puts 'Call sort_by to sort by multiple fields' | |
# pp players.sort_by { |player| [player.avg, player.hr] } | |
# Traceback (most recent call last): | |
# 1: from mets_sort.rb:49:in `<main>' | |
# mets_sort.rb:49:in `sort_by': comparison of Array with Array failed (ArgumentError) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment