I am having one problem to understand the receiver of yield method.
def bar
yield
end
bar { “hello” } # “hello”
Now my question is who is calling the method yield. It is not self,
which is clear from the error below . Now what I know is if we call a
method1 inside a method2, then we can avoid to use explicit self, if
both are method are the instance method of the class self.class. But yield is a method of Proc object. Now how Proc replace there the
role of self ? Is this the exception only with yield ?
def bar
method(:yield) # undefined method ‘yield’ for class ‘Object’
(NameError)
end
Proc#yield is an alias for Proc#call, that is a method of the Proc
class.
But that’s not what a bare yield stands for. A bare yield is a keyword
totally unrelated to Proc#yield.
This is similar to the class keyword. Object#class is a method but in
order
to invoke it you need an explicit receiver, otherwise it is parsed as a
keyword.
I think that is merely an alias for Proc#call. It will just invoke
the block. The keyword yield invokes the block which is an anonymous
function. You can do that explicitly by using #call or #yield
methods:
irb(main):006:0> def f(&b) b.call(123) end
=> nil
irb(main):007:0> f {|x| puts x}
123
=> nil
As you can see the &b stores the block as a Proc in local variable “b”:
irb(main):008:0> def f(&b) p b; b.call(123) end
=> nil
irb(main):009:0> f {|x| puts x}
#Proc:0x00000600407170@:9(irb)
123
=> nil
Proc#yield is an alias for Proc#call, that is a method of the Proc
class.
But that’s not what a bare yield stands for. A bare yield is a keyword
totally unrelated to Proc#yield.
This is similar to the class keyword. Object#class is a method but in
order
to invoke it you need an explicit receiver, otherwise it is parsed as a
keyword.
Nice explanation.
Thanks to every one.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.