在运行时将实例方法设为私有
在另一个对象中注册该对象后,我需要将一些实例方法设为私有。
我不想冻结该对象,因为它必须保持可编辑状态,只是功能较少。我不想取消这些方法的定义,因为它们是在内部使用的。
我需要的是:
class MyClass
def my_method
puts "Hello"
end
end
a = MyClass.new
b = MyClass.new
a.my_method #=> "Hello"
a.private_instance_method(:my_method)
a.my_method #=> NoMethodError
b.my_method #=> "Hello"
有什么想法吗?
I need to make some instance methods private after registering that object in another object.
I don't want to freeze the object because it must remain editable, only with less functionality. And I don't want to undef the methods since they are used internally.
What I need is something like:
class MyClass
def my_method
puts "Hello"
end
end
a = MyClass.new
b = MyClass.new
a.my_method #=> "Hello"
a.private_instance_method(:my_method)
a.my_method #=> NoMethodError
b.my_method #=> "Hello"
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以随时在方法名称上调用方法
private
将其设为私有:或者,从类外部调用:
You can call method
private
on the method name anytime to make it private:or, from outside the class:
什么是公共的,什么是私有的是每个类。但每个对象都可以有自己的类:
但是很糟糕。考虑这些替代方案:
What's public and what's private is per class. But each object can have its own class:
But yuck. Consider these alternatives: