From: "David A. Black" Date: 2007-09-30T03:10:24+09:00 Subject: Re: a = Dog.new # a is not a pointer and not a reference? Hi -- On Sun, 30 Sep 2007, SpringFlowers AutumnMoon wrote: > when we say > > a = Dog.new("lulu") > > Now a is not really a pointer, because we don't need to dereference it > to use it, like > > (*a).color = "red" > a->color = "red" > > When we use a.color, it is like a reference in C++ implicitly > dereference it and use its attributes. > > But then a is not really a reference (like C++), because we can say > > a = nil or a = Dog.new("woofy") > > and now a points to some where else. With reference, once a reference > is set, it cannot point to some where else (in C++). > > So it is kind of a mixture of pointer and reference? It's a reference; at least, that's the term I've always heard Matz and others use, never 'pointer'. When you do this: d = Dog.new("lulu") you have assigned a reference to the dog object to the variable d. As you mention, you don't have to dereference it; you can send messages to an object reference, and they'll go to the object: d.bark # sending message 'bark' to the Dog object When you then do this: d = nil you're starting again, re-using 'd' as an identifier. There's absolutely no connection to the previous use of 'd'. > Or, we can think of it as a pointer, and then think of "." as the "->" > in C++. I would try to think entirely in Ruby. It never quite works to transliterate one language's semantics into another's. The '.' means: send the following message to the object on the dot's left, where the object can be a literal, a variable, or a method call: a = "abc" a.upcase "abc".upcase def d Dog.new("lulu") end d.bark > In that case, we can say that a is a pointer and not a reference. I wouldn't say it's a pointer. "Reference" is the universal term, as far as I've heard. One thing to keep in mind about objects and references in Ruby is that every reference to an object is exactly one step away from the object, and there are no references to references. So you never get into pointer arithmetic and chaining. David -- Upcoming training from Ruby Power and Light, LLC: * Intro to Ruby on Rails, Edison, NJ, October 23-26 * Advancing with Rails, Edison, NJ, November 6-9 Both taught by David A. Black. See http://www.rubypal.com for more info!