复制/继承Ruby Matrix类(core/std lib) [英] Copy/Inheritance of Ruby Matrix class (core/std lib)

查看:92
本文介绍了复制/继承Ruby Matrix类(core/std lib)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在Ruby中扩展现有的Singleton类,例如Matrix类.

I tried to extend an existing Singleton class in Ruby, as an example the Matrix class.

我的第一个 quick& dirty 解决方案是一个猴子补丁(重新打开类并扩展了功能).

My first quick&dirty solution was a monkey patch (reopen class and extend with functionality).

但是我认为,通常猴子打补丁不好,特别是如果有人试图覆盖核心类的基本方法,例如String,Integer,...

But I think, monkey patching in general isn't good, especially if someone tries to overwrite basic methods of core classes like in String, Integer, ...

下一步是找出如何获得具有新名称(如MatrixExt)的Matrix类的真实硬拷贝,该名称表现为独立的单例.

Next step was to find out, how I can get a real hard copy of the Matrix class with a new name (like MatrixExt) which behaves as a standalone singleton.

MatrixExt = Matrix

不是工作,因为它会导致:

didn't the job, as it results in:

MatrixExt.scalar(2,0)
=> Matrix[[0, 0], [0, 0]]

所以我只为同一个单例获得多个名称.不是我想要的.

So I only get multiple names for same singleton. Not, what I want.

clonedup方法的结果相同.

类继承也不起作用:

class MatrixExt < Matrix
  # patches ...
end

MatrixExt.scalar(2,0)
=> Matrix[[0, 0], [0, 0]]

这是最令人困惑的部分,因为在自定义类中,可以获取继承的类. (所以,为什么core/std lib类工作不同?)

And that was the most confusing part, because in self defined classes it is possible to get an inherited class. (So, why the core/std lib classes work different?)

我当前的解决方案是拥有一个扩展模块,然后在初始化后显式使用.extend,例如:

My current solution is to have a module with extension and then explicitly use .extend after initializing, like:

m = Matrix.scalar(2,0).extend(MatrixExtModule)

现在还可以,但是我的问题是:

That is okay for now, but my question is:

还有其他解决方案吗?-是的时候-怎么做?

(不,当然,复制matrix.rb不是一个好方法.; o)

我做错了什么或我在哪里以错误的方式思考?

在此先感谢您提供解决方案和/或提供思想服务!

Thanks in advance for any solution and/or food for thoughts!

推荐答案

这是一个错误.

我已经在redmine.ruby-lang.org 上创建了问题建议您修复这些问题.

I've created an issue on redmine.ruby-lang.org, which is the recommended thing to do to get these fixed.

我修复了该库,但恐怕要等到Ruby 1.9.4才能使用.

I fixed the library, but I'm afraid it won't be available until Ruby 1.9.4.

这篇关于复制/继承Ruby Matrix类(core/std lib)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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