Created
March 13, 2015 19:27
-
-
Save hammerdr/9db2e37be67851a09391 to your computer and use it in GitHub Desktop.
Fancy sort 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
Animal = Struct.new(:name, :height, :legs) | |
animals = [ | |
Animal.new('dog', 10, 4), | |
Animal.new('cat', 5, 4), | |
Animal.new('snake', 2, 0), | |
Animal.new('sloth', 5, 4), | |
Animal.new('ant', 1, 6) | |
] | |
ASCENDING = 'ascending' | |
DESCENDING = 'descending' | |
class Order < Struct.new(:order, :value) | |
def <=>(other) | |
if order == ASCENDING | |
value <=> other.value | |
else | |
other.value <=> value | |
end | |
end | |
end | |
def sort(values, key, order=ASCENDING) | |
values.sort_by { |value| Order.new(order, value.send(key)) } | |
end | |
puts sort(animals, 'name', DESCENDING) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment