重载 Ruby 的数组创建简写

发布于 2024-12-15 11:14:24 字数 441 浏览 1 评论 0原文

我编写了一个库,它通过主要通过方法别名来观察包装器来扩展几个基本 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

混吃等死 2024-12-22 11:14:24

不幸的是,与地球上几乎所有其他编程语言一样,Ruby 不允许文字重载。如果您需要文字重载,则必须使用支持它的少数编程语言之一,例如 IokeSeph

这是 Ioke 中的一个示例:

[] = method(foo, foo println)
[1]
; 1

在 Seph 中:

[] = #(foo, foo println)
[1]
; 1

[请注意,这些当然会对您的系统造成严重破坏,因为,例如,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:

[] = method(foo, foo println)
[1]
; 1

And in Seph:

[] = #(foo, foo println)
[1]
; 1

[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.]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文