问题
I'm trying to make all Hashes in my program be ActiveSupport::OrderedHash.
I can override the Hash.new constructor by ::Hash = ActiveSupport::OrderedHash
but {}.class
is still hash.
def {}
gives me a syntax error.
It was recommended that this is a duplicate of this question, but I don't think that is the case. My question isn't about subclassing Hash, it's about overwriting the default { }
=> Hash constructor.
回答1:
Hash literal {}
is hard-coded in Ruby, and you cannot change it. {}
will become a Hash
. However, since Ruby's class can be modified, you can remove all unnecessary methods, constants, variables from Hash
, and copy everything that is in ActiveSupport::OrderedHash
into Hash
.
回答2:
There are only very few languages which allow you to overload literals (I only know of two: Ioke and Seph). Ruby is not one of them.
See also overloading Ruby's […] Array creation shorthand, Which method is invoked by […] in Ruby?, and How to intercept the call to constructor of class Hash?.
来源:https://stackoverflow.com/questions/34422426/is-there-a-way-to-overwrite-the-object