How to dynamically define a class method which will refer to a local variable outside?

Viewed 17741
class C
end

var = "I am a local var outside"

C.class_eval do
   def self.a_class_method
     puts var 
   end
end

I know, this is not correct, because the def created a new scope. I also know that use define_method can create a instance method without creating a new scope, but my point is how to define a class method.

3 Answers
C.instance_eval do
  def class_method
    "This is class method"
  end
end

instance_eval: defines singleton methods on the object (which results in class methods when it's called on class object).

class_eval: defines regular instance methods

Related