Forum: Ruby Why does this work?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Garth W. (Guest)
on 2006-01-01 01:45
(Received via mailing list)

thread = do |thisThread|
       # thisThread.exit
        puts "object id = #{thisThread.object_id}"

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?

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


Dominik B. (Guest)
on 2006-01-01 03:18
(Received via mailing list)
On Sun, 01 Jan 2006 00:42:46 +0100, Garth W. 

> 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) do |this_thread|
	puts "object id = #{this_thread.object_id}"
	puts "thread id = #{Thread.current.object_id}"
	rescue Exception => e
		p e
p thread.object_id
p a.object_id
p a

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

Code like

x = x + 1

without defining x before this line works, because after the parser saw
=", 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)

Garth W. (Guest)
on 2006-01-01 12:31
(Received via mailing list)
Thanks Dominik,

That explains everything.

This topic is locked and can not be replied to.