Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

482
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!