我想這樣做如下:紅寶石:打印(上下文和exec)任意方法的代碼
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?優選地,它們應該用於任何任意方法,而不必事先知道它們可能碰巧已經被定義或來源於哪裏。
- 是的,我知道方法和塊不完全相同。但這更接近收益率和通話的收益率;我不知道更好的解決方案。
那些地方打印輸出。你可以修改/澄清這些方法中每一種的作用嗎? – 2009-06-12 05:28:00
爲什麼你需要這個? – 2009-06-12 05:31:57