From: Brian Candler Date: 2003-06-01T06:04:54+09:00 Subject: Re: newbie questions On Sun, Jun 01, 2003 at 05:45:43AM +0900, Steven Ketcham wrote: > I am probably confusing concepts but in C++ you can pass a parameter by reference, pointer or value. Copy constructors, > variable scope and things like that are very important to track. If I pass a complex object by value to a function, the copy > of the object will automatically run it's destructor when the function > returns. This could be devasting when working with file or database handles. > > How are objects handled when passed to a function with Ruby? - the thing passed is always a reference to an object (even if it's just a number! Numbers are [immutable] objects in Ruby) - the object is never destroyed until the mark-and-sweep garbage collector finds that it is not being referenced from anywhere. The nearest equivalent to a destructor is the "finalizer", but I have never had a use for it myself. - although almost everything is an object in Ruby, local variables are not: they contain a reference to an object, but you cannot get a reference to the variable itself. a = Foo.new bar(a) # 'bar' can modify the object which 'a' refers to, but # it cannot change 'a' to point to a different object [*] Regards, Brian. [*] This is not strictly true, as you can pass a block or proc object (closure) which binds to a local variable: def bar yield "hello" end a = 123 puts a.id bar { |x| a=x } p a # >> a now points to a String object puts a.id But this is cheating - you are not passing a reference to the variable 'a' itself, but rather a reference to a piece of code which modifies the variable 'a'