Skip to content

Instantly share code, notes, and snippets.

@5alamander
Created May 13, 2016 13:29
Show Gist options
  • Save 5alamander/dc409666900321e27864bf3ce40ed3f9 to your computer and use it in GitHub Desktop.
Save 5alamander/dc409666900321e27864bf3ce40ed3f9 to your computer and use it in GitHub Desktop.
ruby Ordered-hash, add method to a eigen-class
hash={}
hash.instance_eval do # if you want this for all hashes, replace this line with class Hash
def []=(key,val)
ordered_keys << key
super(key,val)
end
def ordered_keys
@ordered_keys ||= []
end
def delete(key)
ordered_keys.delete(key)
super(key)
end
def each_in_order(&block)
ordered_keys.each do |key|
yield(key, self[key])
end
end
end
hash['january'] = 'foo'
hash['february'] = 'bar'
hash['march'] = 'meow'
puts hash.ordered_keys.inspect
puts hash.inspect
hash.delete('february')
puts "deleted feb"
puts hash.ordered_keys.inspect
puts hash.inspect
hash.each_in_order do |key, val|
puts "key: #{key} val: #{val}"
end
["january", "february", "march"]
{"january"=>"foo", "february"=>"bar", "march"=>"meow"}
deleted feb
["january", "march"]
{"january"=>"foo", "march"=>"meow"}
key: january val: foo
key: march val: meow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment