From: Robert Klemme Date: 2006-07-06T23:55:14+09:00 Subject: Re: attribute reader ChrisH wrote: > Just Another Victim of the Ambient Morality wrote: >> "Robert Klemme" wrote in message >> news:4h1o45F1p7ma2U1@individual.net... >>> class Times >>> attr_accessor :time >>> >>> def time_seconds >>> self.time.sec >>> end >>> >>> def now >>> self.time = Time.now >>> end >>> end >> As an aside, I'm still learning Ruby and am curious to know why you >> choose to use self.time instead of @time. Is there some sort of gatcha >> about using instance variables (object variables?) that I don't know about? >> Thank you... > > attr_accessor :time creates an attribute (@time) and two accessor > methods: > def time > #return the value in our attribute > @time > end > > def time=(other) > #set the attribute to the given value > @time = other > end > > > self.time.sec calls the time method of self to get the value of @time > and calls the method sec on it > > self.time = Time.now assigns the value of Time.now to the attribute via > the time= method of self. > cheers That's how it technically works. The *reason* I choose to do that is that the accessor method provides more abstraction. If a sub class chooses to override this method all will still work as expected whereas directly using the instance variable is more likely to break. Another thing to keep in mind is for example, if the implementation of attr_accessor changes and the value thusly is not stored in @time but somewhere else - self.time will then still work whereas direct access to the member will break. And you have to use "self.time=" instead of "time=" because the latter will create a local variable of that name. Kind regards robert