有没有办法覆盖 `{ }` 对象? [英] Is there a way to overwrite the `{ }` object?

查看:77
本文介绍了有没有办法覆盖 `{ }` 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使程序中的所有哈希都成为 ActiveSupport::OrderedHash.

I'm trying to make all Hashes in my program be ActiveSupport::OrderedHash.

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

I can override the Hash.new constructor by ::Hash = ActiveSupport::OrderedHash but {}.class is still hash.

def {} 给我一个语法错误.

建议这是这个问题的副本,但我认为情况并非如此.我的问题不是关于 Hash 的子类化,而是关于覆盖默认的 { } => Hash 构造函数.

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.

推荐答案

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

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.

这篇关于有没有办法覆盖 `{ }` 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆