vivek kumar
vivek kumar

Reputation: 179

Difference between yield self and yield?

Could anyone please help me to understand the difference between "yield self" and "yield"?

class YieldFirstLast
    attr_accessor :first, :last

    def initialize(first = nil, last = nil)
        @first = first
        @last = last
        yield self if block_given?
    end

    def hello
        puts "#{@first} #{@last} says hello!"
    end
end

Upvotes: 13

Views: 7131

Answers (3)

Aldee
Aldee

Reputation: 4528

Think of yield as invoking your block and yield self is invoking your block with the current instance as the parameter.

Upvotes: 2

numbers1311407
numbers1311407

Reputation: 34072

In the case of yield self, self is the argument passed to the block. With simply yield, no argument is passed. self is not special here, anything could be yielded, e.g.

class Foo
  def a() yield self end
  def b() yield end
  def c() yield "Bar" end
  def d() yield 1, 2, "scuba" end
  def to_s() "A!" end
end

Foo.new.a {|x| puts x } #=> A!
Foo.new.b {|x| puts x } #=> (a blank line, nil was yielded)
Foo.new.c {|x| puts x } #=> Bar
Foo.new.d {|x, y, z| puts z } #=> scuba

Upvotes: 21

Victor Deryagin
Victor Deryagin

Reputation: 12225

yield self enters block, associated with method call, passing current object as argument to the block, plain yield just enters the block without passing any arguments.

Upvotes: 5

Related Questions