有没有办法覆盖`{}`对象?

时间:2015-12-22 18:41:39

标签: ruby-on-rails ruby activesupport

我试图让我的程序中的所有哈希都成为ActiveSupport :: OrderedHash。

我可以通过::Hash = ActiveSupport::OrderedHash覆盖Hash.new构造函数,但{}.class仍然是哈希。

def {}给出了语法错误。

建议这是this question的副本,但我不认为是这种情况。我的问题不是关于Hash的子类化,而是关于覆盖默认的{ } =>哈希构造函数。

2 个答案:

答案 0 :(得分:3)

哈希文字{}在Ruby中是硬编码的,你无法改变它。 {}将成为Hash。但是,由于可以修改Ruby的类,您可以从Hash中删除所有不必要的方法,常量和变量,并将ActiveSupport::OrderedHash中的所有内容复制到Hash

答案 1 :(得分:2)

只有极少数语言允许你重载文字(我只知道两个:IokeSeph)。 Ruby不是其中之一。

另请参阅overloading Ruby's […] Array creation shorthandWhich method is invoked by […] in Ruby?How to intercept the call to constructor of class Hash?