Sangaku
Sangaku

Reputation: 95

How can user input dynamically create objects?

I would like users to be able to dynamically create objects of the Incomes class below. That is, I would like to fire my program and let users enter as many incomes as they like, all stored as instances of the Incomes class.

def prompt
puts "> "
end

class Incomes
def initialize(aName, aAmount, aCOLA)
@name = aName
@amount = aAmount
@COLA = aCOLA
end
end

def addIncome
puts "What is the company name?"
prompt
aName = gets.chomp
puts "What is the monthly amount?"
aAmount = gets.chomp
puts "What is the cost of living adjustment?"
aCOLA = gets.chomp
end
#Now I want to be able to loop back through addIncome and create as many objects as the
#user wants. Perhaps there's a better way to store this type of data?

Upvotes: 1

Views: 944

Answers (1)

vgoff
vgoff

Reputation: 11313

def prompt question
  print "#{question} > "
  gets
end

class Incomes
  attr_reader :name, :amount, :COLA
  @@instances_of_Incomes = Array.new
  def initialize(aName, aAmount, aCOLA)
    @name = aName
    @amount = aAmount
    @COLA = aCOLA
    @instances_of_Incomes = Array.new
  end

  def self.addIncome
    name = prompt "What is the company name?"
    amount = prompt "What is the monthly amount?"
    _COLA = prompt "What is the cost of living adjustment?"
    @@instances_of_Incomes << Incomes.new(name, amount, _COLA)
  end

  def self.instances
    @@instances_of_Incomes
  end
end

5.times do
  Incomes.addIncome
end
puts Incomes.instances
Incomes.instances.each do |company|
  puts company.name
end

I have refactored the code to show that you can use inputs to create the instances. They are unnamed classes, but stored in a class variable.

I also show that you can extract the name of each Incomes instance.

I have also edited your SE Code Review question, with the same code, so hopefully you can get some good reviews.

Upvotes: 1

Related Questions