On Sun, 01 Jan 2006 00:42:46 +0100, Garth Williams <garth / penrhiw.net>  
wrote:

> Hi,
>
> thread = Thread.new(thread) do |thisThread|
>        # thisThread.exit
>         puts "object id = #{thisThread.object_id}"
> end
>
> The code above seems to work, thisThread is the same as thread (proved  
> by uncommenting out the line), however in most languages this would not  
> work (I would expect thisThread to be nil), why does it work in ruby and  
> is it considered good practice?

It doesn't work:

this_thread is nil, so this_tread.exit just calls the private method  
Kernel#exit with a receiver, this is not allowed, so an exception is  
thrown and the thread terminates, but you don't see the exception. The  
following code should make it clear:

thread = Thread.new(a = thread) do |this_thread|
	puts "object id = #{this_thread.object_id}"
	puts "thread id = #{Thread.current.object_id}"
	begin
		this_thread.exit
	rescue Exception => e
		p e
	end
end
p thread.object_id
p a.object_id
p a

Output:
object id = 4
thread id = -604525186
#<NoMethodError: private method `exit' called for nil:NilClass>
-604525186
4
nil


Code like

x = x + 1

without defining x before this line works, because after the parser saw "x  
=", it knows that x is a variable, so "x" later returns nil (which seems  
to be the default value for an uninitialized variable).

The above code results in:

irb(main):027:0> x = x + 1
NoMethodError: undefined method `+' for nil:NilClass
         from (irb):27
         from :0

> Also is there a better way to access the current thread?

Thread.current (see above)

Dominik