From: benjohn@... Date: 2006-05-11T19:02:38+09:00 Subject: Re: plz help with binding > Ruby guru, please help: > > I'm creating variable-less storage, wich works fine: > # > def arr_fn() ; arr=[] ; lambda{ arr } ; end > fa = arr_fn ; fa[] << 10 > fb = arr_fn ; fb[] << 20 > p fa[] #=> [10] > p fb[] #=> [20] > # note that fa, fb have different binding for local arr - as expected > > Now I'm trying to create instance-var-less storage: > # > class C > def self.arr_meth( sym ) > arr = [] > define_method sym.to_sym, lambda{ arr } > end > arr_meth :arm > end > ca = C.new; ca.arm << 10 > cb = C.new; cb.arm << 20 > p ca.arm #-> [10, 20] > p cb.arm #-> [10, 20] > p( ca.arm.eql?( cb.arm ) ) #-> true > # > Why ca.arm, cb.arm share same local variable? > Is it bug or feature? :) You're mad :) But I get you... I think. ca.arm and cb.arm share the same local because they're the same function. In the first example, you're creating a new lambda, that holds a new array, with each call to "arr_fn". In the second example, you're only creating the method "arr" inside the class B once (with the line "arr_meth : arm"). This method (which is sitting in the class B, not in each instance of class B - the instances _share_ it), is what you're later calling, and appending to. :) Totally mad, but thanks, it's a good mind bender. [I really don't mean to sound insulting, by the way, I think you're doing something impressively crazy there - it reminds me of "boxes" in lisp (I think "boxes" is the right term).]