class

OrderedHash

v1.1.6 - Show latest stable - Superclass: Array

Needs to be duplicated from Active Support since its needed before Active Support is available.

Files

  • activesupport/lib/active_support/ordered_options.rb
  • railties/lib/initializer.rb

1Note

is now a subclass of Hash that preserves order (or _is_ a Hash if running Ruby 1.9 or greater)

ColinDKelley ยท Jan 25, 20101 thank

You might not realize it preserves order because it delegates inspect to its super-class, Hash, which doesn't preserve order. But you will see that order is preserved if you iterate or use the keys or values methods:

>> names = ['Amy Irving', 'Jane Doe', 'John Doe', 'John Updike', 'Susan Anthony']
>> ordered = names.group_by { |name| name.split.first }
=> #<OrderedHash {"John"=>["John Doe", "John Updike"], "Amy"=>["Amy Irving"], "Susan"=>["Susan Anthony"], "Jane"=>["Jane Doe"]}>

>> ordered.keys
=> ["Amy", "Jane", "John", "Susan"]

>> ordered.each { |first, full| puts first; full.each { |name| puts "  "+name } }
Amy
Amy Irving
Jane
Jane Doe
John
John Doe
John Updike
Susan
Susan Anthony