1

I want to use the value of a variable in my eval. How can I do that?

The following code snippet:

class Adder
  def initialize(i)
    @i = i
  end

  def method_missing(methodName)
    self.class.class_eval do
        def #{methodName}
          return @i+20
        end
    end
  end
end

Gives the error formal argument cannot be an instance variable on Line 9

4
  • I want to define a function with the name helloworld. Commented Jan 19, 2014 at 9:22
  • You eval is also wrong.. it will throw argument error,, Commented Jan 19, 2014 at 9:23
  • 3
    You should use define_method method to define methods in runtime. Commented Jan 19, 2014 at 9:24
  • 1
    @ShaileshTainwala, if you receive answer to your question, please mark correct answer. Commented Jan 19, 2014 at 11:32

3 Answers 3

3

Eval can take a string, so just construct whatever string you want an pass it to eval.

myString = "helloworld"
eval <<END
  def #{myString}
     puts "Hello World!"
  end
END
Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting an error despite using your suggestion. Can you take a look at the updated question please?
No, you didn't use my suggestion. Look carefully and you will see that you are still trying to pass a block to eval, whereas I passed a heredoc string.
2

Use define_method method to define methods in runtime:

my_string = 'helloworld'
define_method my_string do
  # body of your method
end

If you want to pass arguments to the newly defined method you can do this through the block parameters:

define_method 'method_name' do |arg1, arg2|
  # body of your method
end

Comments

1

For your example,

class Adder
  def initialize(i)
    @i = i
  end

  def method_missing(methodName)
    self.class.send :define_method, methodName do
        return @i+20
    end
      send methodName
  end
end

puts  Adder.new(10).helloworld

This defines the method in the class, using the variable you sent as the variable name.

Here's a working example: http://rubyfiddle.com/riddles/e8bf5

1 Comment

This is quite wired example of how far we can go away from the OP question. Using method_missing to define methods in runtime can give you a several "happy" hours of debug in case if something goes wrong. You should do it with caution.

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.