5

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.method_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?

denniss
  • 17,229
  • 26
  • 92
  • 141
  • 4
    Take a look at [this answer](http://stackoverflow.com/questions/622324/getting-argument-names-in-ruby-reflection/2452307#2452307) and the other answers to the same question. It doesn't provide a way to get all the local variable names used in a method, but it does allow you to get the parameter names given a method name. – mikej Aug 30 '11 at 07:48
  • Can I ask you what is the reason to do that? – Simone Carletti Aug 30 '11 at 07:59
  • I want to create a way for subclasses' methods to check the type of its variable based on the name of the variables. so you can say stringName.. it will check that it is a string. – denniss Aug 30 '11 at 16:27
  • That's rather against the philosophy of ruby. You should use duck typing to ensure the objects passed into a method do what you want. I highly recommend Avdi Grimm's talk "Confident Code", available here: http://confreaks.net/videos/614-cascadiaruby2011-confident-code – joshsz Aug 30 '11 at 19:12
  • Yea I am not doing this because I want to follow the philosophy of Ruby. I just wanna see whether I can do it or not. – denniss Aug 30 '11 at 21:13
  • http://stackoverflow.com/questions/622324/getting-argument-names-in-ruby-reflection/2452307#2452307 I believe this is the best answer for my question. – denniss Sep 04 '11 at 01:10

2 Answers2

0

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.

ayckoster
  • 6,707
  • 6
  • 32
  • 45
0
def self.method_added(method_name)
  p self.instance_method(method_name.to_sym).parameters.collect{|g| g[1]}
end
fjlj
  • 136
  • 3