From: Joel VanderWerf Date: 2002-09-26T03:29:57+09:00 Subject: Re: Newbie, threads Stathy G. Touloumis wrote: > Hello, > > I want to start a thread from within the initialize method. This thread > will sleep for a time and then run a method of the Class being > instantiated. How do I refer to the object from within the block being > passed to the Thread constructor? > > Currently this is what I have but it would seem to me that 'self' will > refer to the thread object. > > def initialize > @guard = Thread.new { > while 1 do > sleep(timout) > self.clean > end > } > end The block is a closure, so self, local vars (like timout), and even instance vars (like @guard), are in the scope of the initialize method. ----------- class A def initialize timout = 1 ### added @guard = Thread.new { while 1 do sleep(timout) self.clean end } end def clean puts "Cleaning..." end end A.new sleep(20) ------------ Cleaning... Cleaning... Cleaning...