2014-10-17 60 views
1

我有一個模塊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 

但顯然,這並不工作,因爲我得到一個字符串,而不是一個對象實例。將一組實例發送給一個可以管理它們的可枚舉集合類的正確方法是什麼?

回答

0

我不確定什麼「作爲輸入發送到Portfolio」手段;班級本身不接受「投入」。但如果你只是想Investment對象添加到@investments實例變量的Portfolio實例裏面,試試這個:

portfolio = Portfolio.new([]) 

FDParser.investment_data.each do |data| 
    portfolio.investments << Investment.new(data) 
end 

請注意,數組字面[]portfolio.investments點到返回值的自同數組對象在這裏。這意味着你能等效地做到這一點,這可以說是略知一二:

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) 

雖然我覺得這比以前的選項有點難讀。