Created
December 31, 2009 00:46
-
-
Save arnab/266530 to your computer and use it in GitHub Desktop.
Sort an enumerable (animals) given a specific order (animal_class_order). Important Lines: 22-24
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
animals = [ | |
{ :name => 'Frog', :class => 'Amphibian' }, | |
{ :name => 'Butterfly', :class => 'Arthropod' }, | |
{ :name => 'Eagle', :class => 'Bird' }, | |
{ :name => 'Seahorse', :class => 'Fish' }, | |
{ :name => 'Dog', :class => 'Mammal' }, | |
{ :name => 'Man', :class => 'Mammal' }, | |
{ :name => 'Crocodile', :class => 'Reptile' }, | |
] | |
# Note that Fish and Reptiles are missing from the following | |
animal_class_order = %w(Mammal Bird Amphibian Arthropod) | |
def prettify(animals) | |
animals.map { |a| "#{a[:name]}(#{a[:class]})" }.join(', ') | |
end | |
puts "Unordered: #{prettify(animals)}" | |
sorted_by_name = animals.sort_by { |a| a[:name] } | |
puts "Sorted by name: #{prettify(sorted_by_name)}" | |
num_animals = animals.size | |
sorted_by_animal_class_order = animals.sort_by do |a| | |
animal_class_order.index(a[:class]) || (num_animals + 1) | |
end | |
puts "In Given Animal Class order: #{prettify(sorted_by_animal_class_order)}" | |
__END__ | |
Output: | |
Unordered: Frog(Amphibian), Butterfly(Arthropod), Eagle(Bird), Seahorse(Fish), Dog(Mammal), Man(Mammal), Crocodile(Reptile) | |
Sorted by name: Butterfly(Arthropod), Crocodile(Reptile), Dog(Mammal), Eagle(Bird), Frog(Amphibian), Man(Mammal), Seahorse(Fish) | |
In Given Animal Class order: Dog(Mammal), Man(Mammal), Eagle(Bird), Frog(Amphibian), Butterfly(Arthropod), Seahorse(Fish), Crocodile(Reptile) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment