Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

483
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
over 4 years 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.

over 4 years 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 vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda