【发布时间】:2009-06-12 05:08:46
【问题描述】:
我想做如下的事情:
class String
def fancy_thing appendix
# Just a trivial example to ensure self and params work.
# Pretend this is something complex.
self.reverse + appendix
end
end
# print_method on instance or class should spit out a string
# containing the actual code for that method
ft_code = "cob".print_method :fancy_thing
ft_code = String.print_instance_method :fancy_thing
# => "{|appendix| self.reverse + appendix }" *
# ft_code gets passed around a bit...
# exec on an object should run code (w/ parameters) as if that code is
# an instance method on that object (or class method if it's a class)
"cob".exec(ft_code, '!') #=> "boc!"
如何编写 print_method 和 foo.exec?最好,它们应该适用于任何任意方法,而无需先验地知道它们可能恰好是从哪里定义或来源的。
- 是的,我知道方法和块并不完全相同。但这更接近 yield 和 call 通常需要的值;我不知道有更好的解决方案。
【问题讨论】:
-
您不应该在这两个地方都需要“cob”来打印该输出。您能否修改/澄清有关每种方法的作用的问题...
-
根据我对 joshng 解决方案的评论,目的是 a) 用于 irb/console 目的(在调试器本身之外)和 b) 只是为了看看它是否可能。查看他们所做的修改。
标签: ruby metaprogramming exec