Complete the code to add a method to the class using class_eval.
class MyClass class_eval do def greet puts [1] end end end obj = MyClass.new obj.greet
The string must be quoted to be printed correctly. Using class_eval adds the method to the class.
Complete the code to define an instance variable using instance_eval.
class MyClass def initialize @name = "Ruby" end end obj = MyClass.new obj.instance_eval do @name = [1] end puts obj.instance_eval { @name }
The instance variable @name is set to a string, so it must be quoted.
Fix the error in the code by completing the blank to call instance_eval correctly.
class MyClass def initialize @value = 10 end end obj = MyClass.new result = obj.[1] { @value * 2 } puts result
instance_eval runs the block in the context of the object, allowing access to @value.
Fill both blanks to add a class method using class_eval and call it.
class MyClass [1].class_eval do def self.say_hello "Hello from class method" end end end puts MyClass.[2]
class_eval is called on the class object, and the method say_hello is called on MyClass.
Fill all three blanks to define an instance variable with instance_eval, define a method with class_eval, and call both.
class MyClass [1].class_eval do def greet "Hello, #{@name}!" end end end obj = MyClass.new obj.[2] do @name = [3] end puts obj.greet
class_eval is called on the class to define the method. instance_eval is called on the object to set @name. The name must be a string.