Skip to content

Instantly share code, notes, and snippets.

@hammerdr
Created March 13, 2015 19:27
Show Gist options
  • Save hammerdr/9db2e37be67851a09391 to your computer and use it in GitHub Desktop.
Save hammerdr/9db2e37be67851a09391 to your computer and use it in GitHub Desktop.
Fancy sort in ruby
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