1

我希望用户能够动态地创建以下收入类的对象。也就是说,我想启动我的程序,让用户输入任意数量的收入,所有收入都存储为收入类的实例。

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?
4

1 回答 1

1
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

我重构了代码以表明您可以使用输入来创建实例。它们是未命名的类,但存储在类变量中。

我还展示了您可以提取每个收入实例的名称。

我还使用相同的代码编辑了您的SE 代码审查问题,因此希望您能得到一些好评。

于 2013-07-11T22:57:05.727 回答