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
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@(irb):9>
123
=> nil
Kind regards
robert
···
On Wed, Feb 19, 2014 at 1:33 PM, Arup Rakshit <lists@ruby-forum.com> wrote:
Xavier Noria wrote in post #1137200:
"yield" is not a method, it is a keyword of the language that triggers
hard-coded behavior in the interpreter.
> "yield" is not a method, it is a keyword of the language that triggers
> hard-coded behavior in the interpreter.
>
> Same as "def" or "while" so to speak.
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.
···
On Wed, Feb 19, 2014 at 1:33 PM, Arup Rakshit <lists@ruby-forum.com> wrote:
On Wed, Feb 19, 2014 at 1:33 PM, Arup Rakshit <lists@ruby-forum.com>
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.