有多少种方法可以添加到 ruby 对象中?
当谈到运行时自省和动态代码生成时,我认为除了某些 lisp 方言之外,Ruby 没有任何竞争对手。有一天,我正在做一些代码练习来探索 ruby 的动态功能,我开始想知道向现有对象添加方法的方法。以下是我能想到的 3 种方法:
obj = Object.new
# add a method directly
def obj.new_method
...
end
# add a method indirectly with the singleton class
class << obj
def new_method
...
end
end
# add a method by opening up the class
obj.class.class_eval do
def new_method
...
end
end
这只是冰山一角,因为我还没有探索 instance_eval
、module_eval
和 define_method< 的各种组合。 /代码>。是否有在线/离线资源可以让我了解有关此类动态技巧的更多信息?
When it comes to run time introspection and dynamic code generation I don't think ruby has any rivals except possibly for some lisp dialects. The other day I was doing some code exercise to explore ruby's dynamic facilities and I started to wonder about ways of adding methods to existing objects. Here are 3 ways I could think of:
obj = Object.new
# add a method directly
def obj.new_method
...
end
# add a method indirectly with the singleton class
class << obj
def new_method
...
end
end
# add a method by opening up the class
obj.class.class_eval do
def new_method
...
end
end
This is just the tip of the iceberg because I still haven't explored various combinations of instance_eval
, module_eval
and define_method
. Is there an online/offline resource where I can find out more about such dynamic tricks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Ruby 元编程 似乎是一个很好的资源。 (并且,从那里链接到The Book of Ruby。)
Ruby Metaprogramming seems to be a good resource. (And, linked from there, The Book of Ruby.)
如果
obj
有一个超类,您可以使用define_method
从超类向obj
添加方法 (API) 正如您提到的。如果您查看过 Rails 源代码,您会发现他们做了很多这样的事情。另外,虽然这并不完全是您所要求的,但您可以轻松地给人留下通过使用
method_missing
动态创建几乎无限数量的方法的印象:将其添加到您的类中将允许它响应任何方法调用看起来像
If
obj
has a superclass, you can add methods toobj
from the superclass usingdefine_method
(API) as you mentioned. If you ever look at the Rails source code, you'll notice that they do this quite a bit.Also while this isn't exactly what you're asking for, you can easily give the impression of creating an almost infinite number of methods dynamically by using
method_missing
:Adding that to your class will allow it to respond to any method call which looks like
我喜欢由镐书出版商出版的Metaprogramming Ruby 这本书。
I like the book Metaprogramming Ruby which is published by the publishers of the pickaxe book.