I believe in Ruby, there is a way to access the name of all local variables within a block.
def some_method(param1, param2)
p local_variables
end
whenever 'some_method' is called, param1, and param2 will be printed out. Not the value! but the variable names.
Now, I would like to achieve the same result but within the self.method_added.
Whenever a method is defined, self.method_added is called. I want to be able to access the names of the local variables of the method being defined inside self.method_added. For example,
def self.meth开发者_运维百科od_added(method_name)
#prints the variables names of the argument for method method_name
end
def do_something param1, param2
#crazy stuff
end
with the code above, when do_something is created, I would like to have access to the variable name 'param1' and 'param2'
Is there a way to do this?
def self.method_added(method_name)
p self.instance_method(method_name.to_sym).parameters.collect{|g| g[1]}
end
Depending on your ruby version you might consider ruby2ruby.
See: http://www.slideshare.net/marc_chung/RubyConfRubyDosRuby
It allows you to get an AST (abstract syntax tree) of your code. But last time I checked it worked only with 1.8.
精彩评论