From: Ill Everbe on 4 Jun 2010 13:26 I am trying to keep a history of object state in a parent class using a class variable. This works per example 1 using child method update_state. but if i mixin a module to update_state (so as not to repeat update_state every), per example 2 i get different behavior. i do not understand why. ########################### example 1 ######################## class A def initialize @@history= [] @@incoming_state = ['initial incoming state'] end def update_history @@history = @@history.push( @@incoming_state.flatten) end def history @@history end end class B < A def new_state @another_state = ["new state"] end attr :another_state def update_state @@incoming_state = self.another_state end end a = A.new b=B.new b.new_state b.update_state b.update_history b.update_state b.update_history p b.history ################################ example 2 ################################ class A def initialize @@history= [] @@incoming_state = ['initial incoming state'] end def update_history @@history = @@history.push( @@incoming_state.flatten) end def history @@history end end module Keeper def update_state @@incoming_state = self.another_state end end class B < A include Keeper def new_state @another_state = ["new state"] end attr :another_state end a = A.new b=B.new b.new_state b.update_state b.update_history b.update_state b.update_history p b.history -- Posted via http://www.ruby-forum.com/.
From: Robert Dober on 4 Jun 2010 16:22 On Fri, Jun 4, 2010 at 7:26 PM, Ill Everbe <illeverbe(a)yahoo.com> wrote: Short answer: Do not use class variables, period! Because they are shared amongst subclasses. Long answer: Ok that's exactly what you want.... include Keeper into A and leave the subclasses alone ;) -- The best way to predict the future is to invent it. --Alan Kay
From: Ill Everbe on 4 Jun 2010 17:09 Robert Dober wrote: > On Fri, Jun 4, 2010 at 7:26 PM, Ill Everbe <illeverbe(a)yahoo.com> wrote: > Short answer: Do not use class variables, period! Because they are > shared amongst subclasses. > Long answer: Ok that's exactly what you want.... include Keeper into A > and leave the subclasses alone ;) Much thanks from illeverbe -- Posted via http://www.ruby-forum.com/.
From: Rein Henrichs on 5 Jun 2010 15:15 As a side note: On 2010-06-04 10:26:50 -0700, Ill Everbe said: > def update_history > @@history = @@history.push( @@incoming_state.flatten) > end Array#push modifies the receiver, so you can simply say: def update_history @@history.push(@@incoming_state.flatten) end or even: @@history << @@incoming_state.flatten -- Rein Henrichs http://puppetlabs.com http://reinh.com
|
Pages: 1 Prev: Checking hash tables values in multithread environment Next: Ruby Mendicant University |