Shailesh Tainwala
Shailesh Tainwala

Reputation: 6507

Ruby: How do I use the literal value of a variable in an eval?

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

Upvotes: 1

Views: 362

Answers (3)

Alex Siri
Alex Siri

Reputation: 2864

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

Upvotes: 1

bronislav
bronislav

Reputation: 782

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

Upvotes: 2

David Grayson
David Grayson

Reputation: 87386

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

Upvotes: 3

Related Questions