Is there a way to overwrite the `{ }` object?

半世苍凉 提交于 2020-01-11 11:11:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!