我试图让我的程序中的所有哈希都成为ActiveSupport :: OrderedHash。
我可以通过::Hash = ActiveSupport::OrderedHash
覆盖Hash.new构造函数,但{}.class
仍然是哈希。
def {}
给出了语法错误。
建议这是this question的副本,但我不认为是这种情况。我的问题不是关于Hash的子类化,而是关于覆盖默认的{ }
=>哈希构造函数。
答案 0 :(得分:3)
哈希文字{}
在Ruby中是硬编码的,你无法改变它。 {}
将成为Hash
。但是,由于可以修改Ruby的类,您可以从Hash
中删除所有不必要的方法,常量和变量,并将ActiveSupport::OrderedHash
中的所有内容复制到Hash
。
答案 1 :(得分:2)
只有极少数语言允许你重载文字(我只知道两个:Ioke和Seph)。 Ruby不是其中之一。
另请参阅overloading Ruby's […]
Array creation shorthand,Which method is invoked by […]
in Ruby?和How to intercept the call to constructor of class Hash
?。