Câu hỏi phỏng vấn Ruby
Câu hỏi

What is the difference between BasicObject#i...

Câu trả lời

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

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[1][2][3].

Here's a simple example to illustrate instance_eval:

ruby Copy
class Klass
  def initialize
    @secret = 99
  end
end

k = Klass.new
k.instance_eval { @secret }  # => 99

In this example, instance_eval accesses the @secret instance variable of object k.

BasicObject#instance_exec

BasicObject#instance_exec, on the other hand, is similar to instance_eval in that it also evaluates a block within the context of the receiver object. However, it allows passing arguments to the block. This capability makes instance_exec more flexible when you need to execute a block that requires external parameters[6][12].

Here's an example of instance_exec:

ruby Copy
class KlassWithSecret
  def initialize
    @secret = 99
  end
end

k = KlassWithSecret.new
k.instance_exec(5) { |x| @secret + x }  # => 104

In this example, instance_exec not only accesses the @secret instance variable but also adds it to the parameter x passed to the block.

Summary

The key differences are:

  • Parameter Passing: instance_eval does not allow passing parameters to the block, whereas instance_exec does.
  • Use Case: U...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

Why might you want to alias a method?

middle

What is the difference between Module#remove_method and Module#undef_method ?

middle

What is the difference between Proc invocation and lambda invocation?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào