Topic: Two instances of an object w/ same name

Noob question... What happens to an object if another one is instantiated with the same name? I assume that it is 'overwritten' with the new object of the same name, but I have a class variable that's counting the number of instantiations. It doesn't keep track of this and says there are 2 instantiated objects rather than one (since they are the same name).

class Person
  attr_accessor :first_name, :last_name, :age

  def initialize(age=25)
    @age = age
    @@people = defined?(@@people) ? @@people += 1 : 1

def self.people


john =
p john.inspect
p john.age

john =
p john.inspect
p john.age

p Person.people.to_s + " have been instantiated."

------------- Output: -------------
"#<Person:0x283d20c @age=22>"
"#<Person:0x283d040 @age=27>"
"2 have been instantiated."

Probably not that important in practice, but I was just exploring and ran into a bit of a paradox with the class variable counting new objects even if they are of the same name (which isn't something you would normally do). But thought maybe there's another more fool-proof way of keeping track of instantiated objects? Maybe it's just a curiosity and not really important?

Re: Two instances of an object w/ same name


yes just setting a variable:
i = 1
i = 2
puts i
-> i will be 2 ...

this is basic programming mate tongue

Re: Two instances of an object w/ same name

Ohw and why do you need to keep track of instantiated objects ?

you could do it this way:

a =
3.times do |i|
a <<

puts a.count.to_s

This way you know how many items you have ... just count the items in the array big_smile