Home > OS >  Ruby: Who is self inside a block during yielding?
Ruby: Who is self inside a block during yielding?

Time:09-29

Maybe this is a stupid question, but I can't figure it out. I have a "feeling" why main is self during execution of the block. But I don't have a solid explanation for it.

It seems that the question who is self depends on the context where the block is defined. Is this right?

Can anyone explain it to me?

?> class Klass
?>   def yld
?>     yield
?>   end
>> end

>>
>> o1 = Klass.new
>> o2 = Klass.new
>>
?> o1.yld {
?>   o2.yld {
?>     p self
?>   }
>> }
main

CodePudding user response:

self doesn't change because of a block. The reason you get main is because you are calling yld from the main context:

p self #=> main
o1.yld {
  p self #=> main
  o2.yld {
    p self #=> main
  }
  p self #=> main
}
p self #=> main

However, self can be changed explicitly, e.g. via instance_eval:

def foo(&block)
  "hello".instance_eval(&block)
end

p self #=> main
foo {
  p self   #=> "hello"
  p size   #=> 5
  p upcase #=> "HELLO"
}
p self #=> main

In the above code, self is changed to the string instance "hello" during the block.

  • Related