向实例对象添加方法 [英] Add method to an instanced object
本文介绍了向实例对象添加方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
obj = SomeObject.new
def obj.new_method
"do some things"
end
puts obj.new_method
> "do some things"
这行得通.但是,我需要在现有方法中做同样的事情:
This works ok. However, I need to do same thing inside an existing method:
def some_random_method
def obj.new_method
"do some things"
end
end
也可以正常工作,但是在方法中包含方法看起来非常糟糕.问题是,有没有其他方法可以添加这样的方法?
Works ok as well, but having a method inside a method looks pretty horrible. The question is, is there any alternate way of adding such a method?
推荐答案
好久没问这个问题了.在 ruby 1.9+ 中,有一种更好的方法可以使用 define_singleton_method
,如下所示:
It's been a long time since I asked this. In ruby 1.9+, there's a better way of doing this by using define_singleton_method
, as follows:
obj = SomeObject.new
obj.define_singleton_method(:new_method) do
"do some things"
end
这篇关于向实例对象添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文