Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
据我记得Ruby也有这个功能。动态地向现有类添加方法。但我忘记了如何做到这一点。该功能的名称是什么以及如何做到这一点?
要将方法添加到现有类,只需重新打开该类并定义该方法。
class ExistingClass def new_method ... end end
你也可以使用class_eval:
class_eval
ExistingClass.class_eval do def new_method ... end end
您的所有实例都ExistingClass将获得new_method.
ExistingClass
new_method