Reputation: 6507
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
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
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
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