From: Stefan Lang Date: 2005-07-29T07:30:04+09:00 Subject: Re: self.x=(value) in private? On Friday 29 July 2005 00:24, Stefan Lang wrote: > On Thursday 28 July 2005 23:59, Mark Volkmann wrote: [...] > > An expression that looks like '@attr-name = value' always calls a > > method whose name is 'attr-name='. > > No it's the other way round. Most methods looking like 'attr_name=' > are implemented like this: > > # public accessor method > def attr_name=(val) > # Set instance variable @attr_name > # @attr_name is only accessible in methods of self > @attr_name = val > end > > Let's look at an example: > > % cat foo.rb > class Foo > def initialize > @text = "" > end > def text=(val) > # an empty string is a "true value" in Ruby, > # nil is a "false value" > @text = val || "" > end > def text > # just return @text > @text > end > def set_nil > @text = nil # replace the above line with: # self.text = nil # and the method text= we've defined above will # be called > end > end > > a = Foo.new > a.text = nil > b = Foo.new > b.set_nil > p a.text > p b.text > % ruby foo.rb > "" > nil HTH, Stefan