What is the difference between BasicObject#instance_eval and BasicObject#instance_exec ?
What is the difference between BasicObject#instance_eval and BasicObject#instance_exec ?
The difference between BasicObject#instance_eval and BasicObject#instance_exec in Ruby primarily lies in how they handle block parameters and the context in which they execute code.
BasicObject#instance_eval evaluates a given block or a string of Ruby code within the context of the receiver object. This means that within the block, the self keyword refers to the object on which instance_eval is called. This method is particularly useful for accessing or modifying the instance variables and private methods of the receiver. It does not accept any arguments for the block, meaning you cannot pass parameters directly to the block being evaluated.
Here's a simple example to illustrate instance_eval:
class Klass
def initialize
@secret = 99
end
end
k = Klass.new
k.instance_eval { @secret } # => 99
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.