Last active
December 31, 2015 11:39
-
-
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.
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
# 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