Is 'yield self' the same as instance_eval?

后端 未结 3 441
自闭症患者
自闭症患者 2020-12-24 02:47

Is there any difference if you define Foo with instance_eval: . . .

class Foo
    def initialize(&block)
      instance_eval(&block)         


        
3条回答
  •  我在风中等你
    2020-12-24 03:30

    They are different. yield(self) does not change the value of self inside the block, while instance_eval(&block) does.

    class Foo
      def with_yield
        yield(self)
      end
    
      def with_instance_eval(&block)
        instance_eval(&block)
      end
    end
    
    f = Foo.new
    
    f.with_yield do |arg|
      p self
      # => main
      p arg
      # => #
    end
    
    f.with_instance_eval do |arg|
      p self
      # => #
      p arg
      # => #
    end
    

提交回复
热议问题