Ruby Unbound Methods:是否可以强制绑定到其他类的实例? [英] Ruby Unbound Methods: Is it possible to force bind to instances of other classes?

查看:105
本文介绍了Ruby Unbound Methods:是否可以强制绑定到其他类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以强迫这种情况发生

I would like to know if I could force this to happen

class A
  def bomb ; "bomb" ; end
end

class B ; end

bomb = A.instance_method(:bomb)

b = B.new
bomb.bind(b)

当前它引发错误TypeError:绑定参数必须是A的实例

currently it throws the error TypeError: bind argument must be an instance of A

对于使用这些不受约束的方法可以做些什么,我发现这是非常有限的,可能性是有限的.在这样的情况下(我不仅指幂等函数),这还说得通吗?而且执行错误就足够了,以防万一我要处理A中没有在B中复制的变量.我真的很想知道如何强制执行此绑定.

I find this very limiting concerning what I can do with these unbound methods, the possibilities are a bit limiting. In cases like these (and I'm not referring only to idempotent functions) it would make sense right? And an execution error would have sufficed, In case I would be handling variables from A which are not replicated in B. I'd really like to know how to force this bind.

推荐答案

您不能将一个类的实例与另一个类的方法绑定. 除非instance是此类或其子类的对象.

You cant bind instance of a class with the method of another class. Unless instance is an object of this class, or its sub-classes.

这也很明显,一类的细节不能转移到另一类的实例上.它只能与被授权携带该信息的实例绑定,即该类或其子类的实例.

And this is obvious too, the detail of one class cant be transferred to instance of other class. It can be bound with only that instance which is authorized to carry that information that is, the instance of that class or its sub-class.

因此,ruby还通过不将特定类的方法绑定到另一个类的实例来维护封装.

Hence ruby also maintains encapsulation by not binding method of particular class to instance of another class.

这篇关于Ruby Unbound Methods:是否可以强制绑定到其他类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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