Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Given the following code
- class BaseClass
- end
- class ClassA < BaseClass
- @@instances = []
- attr_accessor :name
- def initialize(name)
- @name = name
- @@instances << self
- end
- def self.list
- @@instances
- end
- def to_s
- @name
- end
- end
- class ClassB < BaseClass
- @@instances = []
- attr_accessor :name
- def initialize(name)
- @name = name
- @@instances << self
- end
- def self.list
- @@instances
- end
- def to_s
- @name
- end
- end
- puts "Creating instanes"
- a = ClassA.new "a"
- aa = ClassA.new "aa"
- b = ClassB.new "b"
- puts "Listing for ClassA"
- puts ClassA.list
- puts "Listing for ClassB"
- puts ClassB.list
- # We get the following output
- bash-3.2$ ./test1.rb
- Creating instanes
- Listing for ClassA
- a
- aa
- Listing for ClassB
- b
- Perfect, however we could do with deduping
- class BaseClass
- @@instances = []
- attr_accessor :name
- def initialize(name)
- @name = name
- @@instances << self
- end
- def self.list
- @@instances
- end
- def to_s
- @name
- end
- end
- class ClassA < BaseClass
- end
- class ClassB < BaseClass
- end
- puts "Creating instanes"
- a = ClassA.new "a"
- aa = ClassA.new "aa"
- b = ClassB.new "b"
- puts "Listing for ClassA"
- puts ClassA.list
- puts "Listing for ClassB"
- puts ClassB.list
- However, when we run this we get
- bash-3.2$ ./test2.rb
- Creating instanes
- Listing for ClassA
- a
- aa
- b
- Listing for ClassB
- a
- aa
- b
- This makes sense because @@instances was defined in the BaseClass and so would be shared between ClassA and ClassB.
- The question is, what is the best way to deduplicate the first example to look more like the second example, but with the correct output?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement