Skip to content

Instantly share code, notes, and snippets.

@kachick
Created May 22, 2012 04:12
Show Gist options
  • Select an option

  • Save kachick/2766504 to your computer and use it in GitHub Desktop.

Select an option

Save kachick/2766504 to your computer and use it in GitHub Desktop.
なにかの断片 - OrderdHash
class OrderdHash
extend Forwardable
extend Container
include Enumerable
def initialize(keys=[], content={})
@keys, @content = keys, content
end
def_delegator :@keys, :each, :each_key
def_delegator :@keys, :dup, :keys
def_delegators :@content, :[], :has_key?
def each_pair
@keys.each{|key|yield key, @content[key]}
end
def each_value
each_key{|key|yield @content[key]}
end
alias_method :each, :each_pair
def []=(key, value)
@keys << key unless @keys.include? key
@content[key] = value
end
def values
map{|key, value|value}
end
def hash
[@keys, @content].hash
end
def ==(other)
hash == other.hash
end
def select
raise ArgumentError unless block_given?
keys = []
content = {}
each_pair do |key, value|
if yield key, value
keys << key
content[key] = value
end
end
self.class.new keys, content
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment