-
Notifications
You must be signed in to change notification settings - Fork 4
Dictionary
The Dictionary class is a variation on Jan Molic's OrderedHash class. As with an ordered hash entries and kept in order, but a Dictionary allows the sorting order of entries to be set via a Proc object. Typically that order will be alphabetical by key, which is why the class is called a Dictionary, but any sorting procedure can be used.
require 'hashery/dictionary'
d = Dictionary['z', 1, 'a', 2, 'c', 3]
d.keys #=> ['z','a','c']
Notice the keys are in the same order as given in the initializer.
d.order_by{ |k, v| k.to_s }
d.keys #=> ['a','c','z']
By setting the sort order via #order_by
, all subsequent iterations or listings will be pre-sorted accordingly.
The way the Dictionary class handles sorting is not very sophisticated. It simply re-sorts the entries every times a call is made that requires them to be so. While it would likely be more efficient to place entries in their sorted position upon assignment, such an update is left to an enthusiastic developer who has a real need for speed ;-)