我有一個模塊FDParser
讀取csv文件,並返回散列的一個很好的陣列,其每一個看起來像這樣:如何從哈希數組創建ruby類的實例?
{
: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
類。
到目前爲止,我嘗試:
FDParser.investment_data.each_with_index do |data, index|
"inv#{index+1}" = Investment.new(data)
end
但顯然,這並不工作,因爲我得到一個字符串,而不是一個對象實例。將一組實例發送給一個可以管理它們的可枚舉集合類的正確方法是什麼?