Created
May 13, 2016 13:29
-
-
Save 5alamander/dc409666900321e27864bf3ce40ed3f9 to your computer and use it in GitHub Desktop.
ruby Ordered-hash, add method to a eigen-class
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
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 |
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
["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