inspired by some lisp magic of runtime edit sourcecode,
I want to do it in ruby. looks like I cannot get sourcecode from method/class,
is there a way to do it?
I write a sample sourcecode here:
def helloworld n
"hello #{n}"
end
o = Kernel.method :helloword
Kernel.define_singleton_method o.name do |n|
eval o.source_code.sub('hello', 'hello world')
end
helloworld 'halida' #=> 'hello world halida'
You can’t get the string representation of a part of the code, edit it and expect Ruby to reevaluate your changes. The only way to do something near to what you want is using
ParseTreeto get s-expressions of the source, edit and useRuby2Rubyto generate a string of ruby code. Them adddef ...andendto the string and call eval with it.It’s too hard and error-prone to be useful in a real-world situation. But I don’t know any other way.
Note: ParseTree only works on Ruby 1.8.