Advertisement
Guest User

Untitled

a guest
Jul 19th, 2013
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.69 KB | None | 0 0
  1. # Given the following code
  2.  
  3. class BaseClass
  4. end
  5.  
  6. class ClassA < BaseClass
  7.  
  8.   @@instances = []
  9.   attr_accessor :name
  10.  
  11.   def initialize(name)
  12.     @name = name
  13.     @@instances << self
  14.   end
  15.  
  16.   def self.list
  17.     @@instances
  18.   end
  19.  
  20.   def to_s
  21.     @name
  22.   end
  23.  
  24. end
  25.  
  26. class ClassB < BaseClass
  27.  
  28.   @@instances = []
  29.   attr_accessor :name
  30.  
  31.   def initialize(name)
  32.     @name = name
  33.     @@instances << self
  34.   end
  35.  
  36.   def self.list
  37.     @@instances
  38.   end
  39.  
  40.   def to_s
  41.     @name
  42.   end
  43. end
  44.  
  45. puts "Creating instanes"
  46. a = ClassA.new "a"
  47. aa = ClassA.new "aa"
  48. b = ClassB.new "b"
  49.  
  50. puts "Listing for ClassA"
  51. puts ClassA.list
  52. puts "Listing for ClassB"
  53. puts ClassB.list
  54.  
  55. # We get the following output
  56.  
  57. bash-3.2$ ./test1.rb
  58. Creating instanes
  59. Listing for ClassA
  60. a
  61. aa
  62. Listing for ClassB
  63. b
  64.  
  65. Perfect, however we could do with deduping
  66.  
  67. class BaseClass
  68.   @@instances = []
  69.   attr_accessor :name
  70.  
  71.   def initialize(name)
  72.     @name = name
  73.     @@instances << self
  74.   end
  75.  
  76.   def self.list
  77.     @@instances
  78.   end
  79.  
  80.   def to_s
  81.     @name
  82.   end
  83. end
  84.  
  85. class ClassA < BaseClass
  86. end
  87.  
  88. class ClassB < BaseClass
  89. end
  90.  
  91. puts "Creating instanes"
  92. a = ClassA.new "a"
  93. aa = ClassA.new "aa"
  94. b = ClassB.new "b"
  95.  
  96. puts "Listing for ClassA"
  97. puts ClassA.list
  98. puts "Listing for ClassB"
  99. puts ClassB.list
  100.  
  101. However, when we run this we get
  102.  
  103. bash-3.2$ ./test2.rb
  104. Creating instanes
  105. Listing for ClassA
  106. a
  107. aa
  108. b
  109. Listing for ClassB
  110. a
  111. aa
  112. b
  113.  
  114. This makes sense because @@instances was defined in the BaseClass and so would be shared between ClassA and ClassB.
  115.  
  116. 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