Created
October 5, 2011 18:17
-
-
Save heyLu/1265214 to your computer and use it in GitHub Desktop.
Overriding Hash#[] from a module
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
# So, this version is not at all mine, it's one from @samuelkadolph. | |
# (Just for the record.) | |
class MyHash < Hash | |
def initialize(hash = {}) | |
super() | |
merge!(hash) if hash | |
end | |
def [](key) | |
return super(key.to_s) if key?(key.to_s) | |
return super(key.to_sym) if key?(key.to_sym) | |
end | |
end | |
module M | |
def self.included(klass) | |
klass.class_eval do | |
alias_method :original_indexer, :[] | |
alias_method :[], :new_indexer | |
end | |
end | |
def new_indexer(key) | |
return original_indexer(key.to_s) if key?(key.to_s) | |
return original_indexer(key.to_sym) if key?(key.to_sym) | |
end | |
end | |
class MyHash2 < Hash | |
include M | |
end | |
h1 = MyHash.new(:a => 2) | |
h1["a"] # => 2 | |
h2 = MyHash2.new | |
h2[:a] = 2 | |
h2["a"] # => 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment