From: "Jesús Gabriel y Galán" Date: 2012-11-28T01:20:49+09:00 Subject: Re: why this behaves like singleton On Tue, Nov 27, 2012 at 5:00 PM, Javier Isassi wrote: > The attached code prints: > > print g1 locks > 5 > print g2 locks > 5 > 3 > > > I would expect g2 to print 3. Why the Lock object behaves > like singleton? class Lock @lock = 0 # This variable is not the same as the one used below in initialize and glock methods. The reason is that @xxx refers to an instance variable of the object that happens to be self in that scope, and in this case the object is the Lock class itself, while in the initialize and glock methods, it's a specific instance of the Lock class. So, in summary, you can remove this line. def initialize(r) @lock = r end def glock() @lock end end class Locks @@locks = [] # A variable prefixed with @@ is a class variable. It is shared among the class and all its subclasses. Every reference to this variable in this scope or in instance methods of this class or any subclass will refer to the same object. You most certainly don't want this. So remove this and change it with @locks = [] inside the initialize method, which creates an instance variable of the object being initialized. def initialize ( rd ) rd.each do |k| @@locks << Lock.new(rd) end end def printLocks @@locks.each do |l| puts l.glock() end end end I would try: class Lock attr_reader :lock def initialize r @lock = r end end class Locks def initialize lock_ids @locks = [] lock_ids.each {|id| @locks << Lock.new(id)} end def print_locks @locks.each {|lock| puts lock.lock} end end 1.9.2p290 :019 > g1 = Locks.new([5]) => #]> 1.9.2p290 :020 > puts "print g1 locks" print g1 locks => nil 1.9.2p290 :021 > g1.print_locks 5 => [#] 1.9.2p290 :022 > g2 = Locks.new([3]) => #]> 1.9.2p290 :023 > puts "print g2 locks" print g2 locks => nil 1.9.2p290 :024 > g2.print_locks 3 Jesus.