Skip to content

Instantly share code, notes, and snippets.

@kajic
Last active December 31, 2015 11:39
Show Gist options
  • Save kajic/7981533 to your computer and use it in GitHub Desktop.
Save kajic/7981533 to your computer and use it in GitHub Desktop.
HashOfArray keeps track of the combined order in which elements are appended to its arrays.
# HashOfArray keeps track of the combined order in which elements are appended to its
# arrays.
# HashOfArray.items returns all items appended to the arrays, in the order they were
# appended.
#
# Example:
#
# h = HashOfArray.new
#
# h[:a] << 1
# h[:b] << 2
# h[:a] << 3
# h[:b] << 4
#
# h.items => [1, 2, 3, 4]
class HashOfArray < Hash
attr_accessor :items
def initialize
self.items = []
super { |h, k| h[k] = Arr.new(self) }
end
class Arr < Array
attr_accessor :parent
def initialize(parent)
self.parent = parent
end
def <<(value)
parent.items << value
super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment