difference between @var and self.var

S

Shea Martin

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 and
@my_member? 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.

~S

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.
 
T

Timothy Goddard

Remember that in Ruby that you cannot directly access the instance
variables of an object. When you call a.b you're really calling the 'b'
method on a. These methods are generated by the attr functions. self is
the current object, so you can only call methods on it. @var is the
actual instance variable while self.var is the result of calling the
var method.
 
S

Shea Martin

Jeffrey said:
A method.


A variable.

Thanks, it seems dead obvious now. :-(


I don't know yet know as much as I would like
about Rails, though. :(

<rant>
Well it is worth learning. I have done dynamic sites in PHP before, but
doing this site with Rails makes me giddy. It is really the same
elation as learning ruby. Ruby made programming feel less like work,
and more like play. Rails actually made web programming fun (something
I thought would never happen again).
</rant>

~S
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top