eval vs instace_eval vs class_eval

The main difference between eval and instance_eval in Ruby lies in the context in which they execute code.

  1. eval:

    • The eval method is a core Ruby method that allows you to evaluate and execute a string of Ruby code.

    • It executes the code within the current scope, meaning it has access to local variables and can modify them.

    • eval can be used to execute arbitrary code and can access variables from the surrounding context.

    • It is typically used when you have a string representation of Ruby code that needs to be executed dynamically.

    Example:

    x = 10
    eval("puts x")  # Output: 10

    In this example, eval executes the code within the current scope, so it can access and print the value of the x variable.

  2. instance_eval:

    • The instance_eval method is defined in Ruby's BasicObject class and is used to evaluate a block of code within the context of a specific object.

    • It changes the context or self within the block to be the object on which instance_eval is called.

    • instance_eval provides a way to execute code as if it were defined within the object itself, allowing access to its instance variables and private methods.

    • It is often used for metaprogramming purposes, such as dynamically defining methods or modifying an object's behavior.

    Example:

    class MyClass
      def initialize(x)
        @x = x
      end
    end
    
    obj = MyClass.new(42)
    obj.instance_eval do
      puts @x
    end

    In this example, instance_eval is used to execute the code within the context of the obj object. Inside the block, @x refers to the instance variable of obj, and its value (42) is printed.

In summary, the key distinction is that eval executes code within the current scope and can access local variables, while instance_eval changes the context to the specified object and allows access to its instance variables and private methods. Both methods serve different purposes in metaprogramming and dynamic code execution.

https://www.simplybusiness.co.uk/about-us/tech/2021/01/demystifying-class-eval-and-instance-eval-in-ruby/

Last updated