1

If I create a student class and each time a new student object is created, how do I dynamically create a new variable name to distinguish between the different students? I don't know how many students there will be.

On the last line of the code below I have used student1 as the variable name for the new student object. If I want to create 100 student objects and have the variable name be student1 through student100 how would I dynamically create these variable names?

class Student
  attr_accessor :name

  def initialize(name)
    @name = name
    puts "Hello #{name}"
  end
end

puts "What is your name?"
answer = gets.chomp
student1 = Student.new(answer)
  • 6
    Why don't you just use an array for holding those 100 student objects, each new object creation will be added into that array, then you can access them via index – You Nguyen Jul 01 '19 at 03:24
  • 5
    this is an [XY problem](https://meta.stackexchange.com/a/233676/319720), you really want to use an array like Nguyen said – max pleaner Jul 01 '19 at 04:19
  • To anwer your question, since Ruby v1.9 it has not been possible to create a local variable dynamically. In earlier versions that could be done using `eval`. – Cary Swoveland Jul 01 '19 at 05:08
  • @NathanWorden : Creating a variable - dynamically or not - means that you later access the variable in your program by its *name*; otherwise, why create it in the first place? Then I don't see what advantage you have from a dynamical creation. If you want to handle a collection of objects and still somehow give a "name" to the individual objects, use a Hash and make the "name" the hash key. – user1934428 Jul 01 '19 at 06:49

1 Answers1

2

All you need is:

students = Array.new(100) { |i| Student.new("Name #{i}") }

If you want to access the student ith, you can call

students[i]

There's no need to create a local variable called students_13 for example.

The first student is student[0], the last one student[99].

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124