我想做类似以下的事情:
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 通常需要的值;我不知道更好的解决方案。