次のようなことをしたいと思います。
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 に近いものです。私はより良い解決策を知りません。