1

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?

3
  • 2
    you are almost done.. What is stopping you ? Commented Jul 24, 2014 at 20:15
  • Well, I am not sure but block do #stuff end is in the same scope as variable = 5. Even I am wrong, that block has access to a mother's scope*. Check this: a = 42; l =-> do; b = 22; l2 = -> do; puts a; end; end; l.call.call; *I am not sure about proper title so I made up that. Commented Jul 24, 2014 at 20:32
  • I'm confused. The code you have shown does exactly what you want. So, what is your question? Commented Jul 25, 2014 at 0:26

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.