Skip to content

Instantly share code, notes, and snippets.

@arnab
Created December 31, 2009 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnab/266530 to your computer and use it in GitHub Desktop.
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
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