Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

142
Vistas
Ruby: Who is self inside a block during yielding?

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
10 months ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

10 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.