[英]How can I create instances of a ruby class from a hash array?
我有一個模塊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
類 。
到目前為止,我嘗試了:
FDParser.investment_data.each_with_index do |data, index|
"inv#{index+1}" = Investment.new(data)
end
但是顯然這是行不通的,因為我得到的是字符串而不是對象實例。 將實例的集合發送到可以枚舉實例的可枚舉的集合類的正確方法是什么?
我不確定“ 作為輸入發送到Portfolio
類的意思”是什么意思; 類本身不接受“輸入”。 但是,如果你只是想增加Investment
對象的@investments
的實例中的實例變量Portfolio
,試試這個:
portfolio = Portfolio.new([])
FDParser.investment_data.each do |data|
portfolio.investments << Investment.new(data)
end
請注意,數組文字[]
和portfolio.investments
的返回值在此處指向相同的Array對象。 這意味着您可以等效地執行此操作,這可以說更清晰一些:
investments = []
FDParser.investment_data.each do |data|
investments << Investment.new(data)
end
Portfolio.new(investments)
而且,如果您想打一點代碼高爾夫,那么使用map
,它會進一步縮小。
investments = FDParser.investment_data.map {|data| Investment.new(data) }
Portfolio.new(investments)
我認為這比以前的選項難讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.