sel*_*eli 6 ruby hash overriding
我想覆盖ruby中的Hash类本机括号.
注意我不想在继承自Hash(没有子类化)的类中覆盖它们,我想实际上覆盖Hash本身,这样任何地方的任何哈希都将继承我的行为.
具体来说(奖励积分为......) - 我希望这能够本地模拟具有无差别访问权限的哈希.在JavaScript中我会修改prototype,Ruby以其元编程而闻名,所以我希望这是可能的.
所以我的目标是:
>> # what do I do here to overload Hash's []?...
>> x = {a:123} # x is a native Hash
>> x[:a] # == 123, as usual
>> x['a'] # == 123, hooray!
Run Code Online (Sandbox Code Playgroud)
我试过了:1)
class Hash
define_method(:[]) { |other| puts "Hi, "; puts other }
end
Run Code Online (Sandbox Code Playgroud)
和
class Hash
def []
puts 'bar'
end
end
Run Code Online (Sandbox Code Playgroud)
两个都崩溃了.
这似乎完成了工作.
class Hash
def [](key)
value = (fetch key, nil) || (fetch key.to_s, nil) || (fetch key.to_sym, nil)
end
def []=(key,val)
if (key.is_a? String) || (key.is_a? Symbol) #clear if setting str/sym
self.delete key.to_sym
self.delete key.to_s
end
merge!({key => val})
end
end
Run Code Online (Sandbox Code Playgroud)
现在:
user = {name: 'Joe', 'age' => 20} #literal hash with both symbols and strings as keys
user['name'] == 'Joe' # cool!
user[:age] == 20 # cool!
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅:http://www.sellarafaeli.com/blog/ruby_monkeypatching_friendly_hashes