🌿 What?

  • 🌱 Trong Ruby, class Object có public method là instance_eval(), method này cấp quyền truy cập tới các biến instance của object, nhận vào string chứa code Ruby hoặc block và excute theo context của object.
class Klass
  def initialize
    @secret = 99
  end
end
 
irb(main):001:0> k = Klass.new
irb(main):002:0> k.instance_eval { @secret }
=> 99
# add method
string = "String"
string.instance_eval do
  def new_method
    self.reverse
  end
end
 
irb(main):033:0> string.new_method
=> "gnirtS"
  • 🌱 Tương tự với module và class sẽ có module_eval() và class_eval()

🌿 Refer