【发布时间】:2014-12-12 18:32:47
【问题描述】:
我有一个模块 FDParser,它读取一个 csv 文件并返回一个很好的哈希数组,每个看起来像这样:
{
:name_of_investment => "Zenith Birla",
:type => "half-yearly interest",
:folio_no => "52357",
:principal_amount => "150000",
:date_of_commencement => "14/05/2010",
:period => "3 years",
:rate_of_interest => "11.25"
}
现在我有一个Investment 类,它接受上述哈希作为输入,并根据我的需要转换每个属性。
class Investment
attr_reader :name_of_investment, :type, :folio_no,
:principal_amount, :date_of_commencement,
:period, :rate_of_interest
def initialize(hash_data)
@name = hash_data[:name_of_investment]
@type = hash_data[:type]
@folio_no = hash_data[:folio_no]
@initial_deposit = hash_data[:principal_amount]
@started_on =hash_data[:date_of_commencement]
@term = hash_data[:period]
@rate_of_interest = hash_data[:rate_of_interest]
end
def type
#-- custom transformation here
end
end
我还有一个Porfolio 类,我希望用它来管理investment 对象的集合。这是Portfolio 类的样子:
class Portfolio
include Enumerable
attr_reader :investments
def initialize(investments)
@investments = investments
end
def each &block
@investments.each do |investment|
if block_given?
block.call investment
else
yield investment
end
end
end
end
现在我想要遍历模块产生的investment_data 并动态创建投资类的实例,然后将这些实例作为输入发送到Portfolio 类。。 p>
到目前为止我尝试过:
FDParser.investment_data.each_with_index do |data, index|
"inv#{index+1}" = Investment.new(data)
end
但显然这不起作用,因为我得到的是一个字符串而不是一个对象实例。将实例集合发送到可以管理它们的可枚举集合类的正确方法是什么?
【问题讨论】:
标签: ruby oop collections enumerable