redbarron
redbarron

Reputation: 11

Ruby Metaprograming and passing Parameters

I want to define a method in ruby using

    define_method 

within another function. Example code is below.

def demo(method_name)
    variable = 5
    define_method "#{method_name}" do
        #stuff
    end
end

Inside the newly defined method I want to be able to access the variable:

variable=5

that was previously defined. For example I want to be able to do :

    define_method "#{method_name}" do
        return variable*variable
    end

and get variable squared.

I want to be able to:

demo("squared")
x = squared # => 25 

Is there a way I can pass the variable "variable" into the define_method even though it is not in the same scope?

Upvotes: 1

Views: 67

Answers (1)

Nick Veys
Nick Veys

Reputation: 23939

Sure, and what you have works. What's the problem?

[15] pry(main)> def demo(method_name)    
[15] pry(main)*   variable = 5      
[15] pry(main)*   define_method "#{method_name}" do      
[15] pry(main)*     variable * variable        
[15] pry(main)*   end        
[15] pry(main)* end      
=> :demo
[16] pry(main)> demo('squared')
=> :squared
[17] pry(main)> squared
=> 25

Upvotes: 4

Related Questions