From: Brian Candler Date: 2008-09-20T04:44:58+09:00 Subject: Re: why one array continues to grow after repeated call Just one other thing. All this talk about []= has overlooked the much more common case of methods called "something=". Often they happen to perform assignment to an instance variable, e.g. class Foo def bar @bar end def bar=(x) @bar = x end end f = Foo.new f.bar = 99 # a method call to "bar=" puts f.bar (There's the "attr_accessor" method to help with this common pattern). However there's no requirement for them to do so. For example, if you have a database connection manager class, then you might legitimately write: def autocommit=(flag) if flag @socket.write("set autocommit on;\n") else @socket.write("set autocommit off;\n") end end ... conn.autocommit = true This is changing state of the connection, but doesn't assign to anything in Ruby. Now, there is a subtle trap which I still fall into from time to time. For example, later in the database connection manager class, you may write another method which looks like this: def transaction(sql) autocommit = false @socket.write("begin\n") @socket.write(sql) @socket.write("commit\n") ensure autocommit = true end This runs, but unfortunately doesn't do what was intended. "autocommit = false" just brings a local variable into existence, and sticks false in it. To call the method called "autocommit=" you have to write: self.autocommit = false ... self.autocommit = true That is, you must always qualify these sorts of method calls with a receiver, because an unqualified expression of the form "x = ..." is always taken to be an assignment to a local variable x. Anyway, just another example of why it's important to distinguish an assignment from something that isn't :-) B. -- Posted via http://www.ruby-forum.com/.