Is 'yield self' the same as instance_eval?

Viewed 7176

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

class Foo
    def initialize(&block)
      instance_eval(&block) if block_given?
    end
  end

. . . or with 'yield self':

class Foo
  def initialize
    yield self if block_given?
  end
end

In either case you can do this:

x = Foo.new { def foo; 'foo'; end }
x.foo 

So 'yield self' means that the block after Foo.new is always evaluated in the context of the Foo class.

Is this correct?

3 Answers
Related