Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • class_eval and instance_eval

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 178
    Comment on it

    What is the use of class_eval and instance_eval?

    class_eval and instance_eval allows us to define a method of a class from outside of its original definition and without reopening the class with the standard syntax. This could be useful when you want to add method and make it unknown till runtime.

    Example of class_eval:

    class User
    end
    
    User.class_eval do
      def say_hello
       "Hello!"
      end
    end
    
    user = User.new
    user.say_hello
     => "Hello!"
    

    Example of instance_eval:

    class User
    end
    
    User.instance_eval do
      def say_hello
       "Hello!"
      end
    end
    
    User.say_hello
     => "Hello!"
    

    Summary:

    class_eval allow us to add instance method from outside the class definition and instance_eval allow us to add class method from outside the class definition.

    Behind this madness:

    class_eval is a method of the Module class, meaning that the receiver will be a module or a class. The block you pass to class_eval is evaluated in the context of that class. Defining a method with the standard def keyword within a class defines an instance method.

    instance_eval, on the other hand, is a method of the Object class, meaning that the receiver will be an object. The block you pass to instance_eval is evaluated in the context of that object. That means that User.instance_eval is evaluated in the context of the User object.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: