I want to write a method which takes one parameter and creates another method, named with this parameter. Here is my code
class Class
def createMethod(attr_name)
attr_name = attr_name.to_s
class_eval %Q{
def #{attr_name}
puts "bar"
end
}
end
end
p Class.new.createMethod("foo").respond_to?(:foo)
Unfortunately, respond_to?(:foo)
evaluates to false
. What's wrong?
This is because
class_eval
is a class method and you're calling it in the context of an instance. You can do this instead:Here's the output from
irb
when doing this: