From: Robert Klemme Date: 2007-05-22T22:00:13+09:00 Subject: Re: bug in ruby On 22.05.2007 14:53, Brian Candler wrote: > On Tue, May 22, 2007 at 09:41:03PM +0900, sairam MP wrote: >> class Foo >> attr_accessor :bar >> >> >> def foo >> self.bar = 1 >> >> >> if false >> bar = 2 # never executed >> end >> >> >> p self.bar # prints 1 >> p bar # prints nil >> end >> end > > This is a bug in your understanding of the language, not in the language > itself. You've not said exactly what you think it *should* do instead of > what it does, so it's hard to give an answer tailored to improving your > understandly. > > But briefly: an assignment like "bar = 2" is seen at the time the program is > *parsed* and means that an unqualified "bar" is treated as a local variable > from that point onwards until the end of that scope. Whether or not it is > actually *executed* makes no difference. > > When you write "self.bar" or "self.bar=" you are explicitly making a method > call to a method "bar" or "bar=" on the current object; this is never > treated as a local variable. > > If you write "bar" by itself, this is treated as a method call on the > current object *unless* an assignment of the form "bar = x" has been seen by > the parser earlier in the scope. Additional reference material: http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html#UO Kind regards robert