用户输入如何动态创建对象?

时间:2013-07-11 19:36:07

标签: ruby

我希望用户能够动态创建下面的Incomes类的对象。也就是说,我想解雇我的程序,让用户输入尽可能多的收入,全部存储为Incomes类的实例。

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?

1 个答案:

答案 0 :(得分:0)

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

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

我还表明您可以提取每个Incomes实例的名称。

我还使用相同的代码编辑了您的SE Code Review question,希望您能获得一些好评。