Jeff Schwab
6/21/2006 7:04:00 PM
Shea Martin wrote:
> I have been using Ruby for a while, and thought I had a pretty good
> grasp of the language, but...
>
> In an instance method, what is difference between self.my_member
A method.
> and @my_member?
A variable.
> I though 'self' was like 'this' in C++ or Java, but it
> appears this is not the case. In my class, it seems possible to have
> different values for the two variation.
"self" is very similar to "this," or the "self" of Smalltalk. The need
of context to determine whether an identifier refers to a method or an
instance variable also occurs in C++:
struct B: A {
using A::i;
};
This is seldom a problem in C++ because no instance method may have the
same name as a member variable of the same class. In Java, this kind of
name-sharing is allowed, but methods are rarely referred to without
accompanying parenthesis. One obvious exception is the static import:
/* "i" might name a variable and/or one or more methods. */
import static pkg.A.i;
> ps - this was actually seen in my Rails app, in the model. The member
> variable was one inherited from AR. I was setting it's value like this:
> @my_member = "sdfsdf", but the my_member column was not reflecting the
> change, until I used self.my_member = "asdf". This was in an instance
> method, not class method.
The my_member method may have the side effect of committing the new
value to a database. I don't know yet know as much as I would like
about Rails, though. :(