Pabi
Pabi

Reputation: 994

How to check if an instance name already exists

How can I make it so that each time a new instance of the class User is created, the instance will be named user# (#=a number), so that each user has a different number.

So that it does something like this:

user1 = User.new("user", "password")
user2 = User.new("other_user", "password")
user3 = User.new("other_user", "password")
...

But if user1 already exists I want it so that when it creates a new user it will name it user2 and not recreate user1 and so on.

Upvotes: 0

Views: 707

Answers (1)

spickermann
spickermann

Reputation: 106802

Defining variables the way you think about makes it hard to read the variables later on. Imaging how you want to read the values again? You need to keep track yourself how many variables exist. And there is no need to use meta programming in this case.

A data structure that avoids this problems is an Array that allow you to store elements and read them again by their position within the array:

users = []
users << User.new("user", "password")
users << User.new("other_user", "password")
users << User.new("other_user", "password")

users
#=> returns all users in an array

users.size
#=> returns the number of users in the array

users[0]
#=> returns the first User

users[n]
#=> returns the n User in this array

It looks to me like the OP wants to have (or at least doesn't care about) duplicates. But, if you want to avoid duplicates, you can check for duplicates before adding new elements like this:

user = User.new("other_user", "password")
users << user unless users.include?(user)

Or you could remove duplicates by calling users.uniq.

Upvotes: 3

Related Questions