linjunhalida linjunhalida - 1 year ago 101
Ruby Question

how to get source code text in ruby?

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}"

o = Kernel.method :helloword

Kernel.define_singleton_method do |n|
eval o.source_code.sub('hello', 'hello world')

helloworld 'halida' #=> 'hello world halida'

Answer Source

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 ParseTree to get s-expressions of the source, edit and use Ruby2Ruby to generate a string of ruby code. Them add def ... and end to 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download