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?

6
  • 4
    Take a look at this answer 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. Commented Aug 30, 2011 at 7:48
  • Can I ask you what is the reason to do that? Commented Aug 30, 2011 at 7: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. Commented Aug 30, 2011 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: confreaks.net/videos/614-cascadiaruby2011-confident-code Commented Aug 30, 2011 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. Commented Aug 30, 2011 at 21:13

2 Answers 2

0
def self.method_added(method_name) p self.instance_method(method_name.to_sym).parameters.collect{|g| g[1]} end 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.