重载 Ruby 的数组创建简写
我编写了一个库,它通过主要通过方法别名来观察包装器来扩展几个基本 Ruby 类。但是,我遇到了数组实例化简写的障碍(例如 @a = [1, 2, 3]
),我似乎找不到在创建数组时实际调用的任何方法数组对象通过简写表示。它不是当前作用域中继承的 #[]
方法,也不是从祖先链中的任何类或模块继承的方法。我还重载或监视了 Array 类上从类的 #new
到实例的 #initialize
到 singleton_method #[]
的每个方法基于 Ruby C 代码的对象
rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -1);
有谁知道我如何分配一个位于速记数组实例实例化的方法链内的方法?
I've written a library that extends several base Ruby classes with observing wrappers mostly through method aliasing. However, I've hit a roadblock with the Array instantiation shorthand (e.g. @a = [1, 2, 3]
) I can't seem to find any method that's actually called in the creation of an Array object by the shorthand means. It's not an inherited #[]
method in the current scope or inherited from any class or module in the ancestors chain. I've also overloaded or watched every method from the class's #new
to an instance's #initialize
to the singleton_method #[]
on the Array class object based on the Ruby C code
rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -1);
Does anyone know how I can assign a method that would be within the method chain of the shorthand Array instance instantiation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,与地球上几乎所有其他编程语言一样,Ruby 不允许文字重载。如果您需要文字重载,则必须使用支持它的少数编程语言之一,例如 Ioke 或 Seph。
这是 Ioke 中的一个示例:
在 Seph 中:
[请注意,这些当然会对您的系统造成严重破坏,因为,例如,Ioke/Seph 标准库的很大一部分是在 Ioke/Seph 中实现的,并且它们使用到处都有列出,因此在生产系统中,您需要正确封装它。]
Unfortunately, like pretty much every other programming language on the planet, Ruby does not allow overloading of literals. If you require literal overloading, you will have to use one of the few programming languages which support it, like Ioke or Seph.
Here's an example in Ioke:
And in Seph:
[Note that these will, of course, wreak havoc with your system, since, for example, a large part of the Ioke/Seph standard library is implemented in Ioke/Seph, and they use lists all over the place, so in a production system, you'll want to properly encapsulate this.]