2015-02-10 78 views
0

在我開始寫週末代碼之前,我正在玩Ruby中強制類關係的方法。我在嘗試一種複合關係,但是我有一些對Commodity類以外的PriceSeries類的控制。從實例方法實例化組合類Ruby

顯然這不是,但是有沒有這樣的設置的理由?我是否認爲這會爲私人數據創造價值,並且可能適合存儲用戶實例的密碼?

class ExcelFile 
    def initialize(name) 
     @name = name 
    end 
end 


class Commodity 
    def initialize(name) 
     @name = name 
    end 

    def new_price_series(name, source) 
     name = PriceSeries.new(name, source) 
    end 

    class PriceSeries 
     attr_accessor(:name) #Without this line, is there any point of this class?? 

     def initialize(name, source) 
      @source = source 
      @name = name 
     end 
    end 

end 



mm8_prices = ExcelFile.new("some_exlsx_file") 
gold = Commodity.new("gold") 
gold.new_price_series(:xau, mm8_prices) 

回答

0

你能解釋一下'在Ruby中強制類關係'和'複合關係'是什麼意思嗎?

在Ruby中定義一個類在另一個類中,就像你在例子中所做的那樣,它沒有賦予任何一個類相對於另一個類的特殊特權,它只是爲'inner'類命名空間。即PriceSeries(當在Commodity之外引用時)將是Commodity::PriceSeries

這與在諸如C#和Java等語言中定義內部類不同。

+0

有什麼區別? (我只使用ruby/python/php和javascript)。我想在編碼時明確說明一個PriceSeries實例化屬於一種商品,如果沒有一個商品就不能存在 - 但商品可以不存在價格系列。另外,噸[這裏可以是許多PriceSeries每個商品。我想我實際上已經找到了一種方法來使用元編程來在PricePoint對象的Commodity類中創建實例方法。這是做這件事的好方法嗎? – 2015-02-10 21:51:57

+0

在你的例子中,你只需定義一個名爲Commodity :: PriceSeries的類。 Commodity和PriceSeries或它們的實例之間沒有特別的關係 - PriceSeries可以使用Commodity :: PriceSeries.new(name,source)通過Commodity之外的代碼實例化。要強制執行關係,請將商品實例傳遞給PriceSeries構造函數。您的Commodity實例還可以維護一組PriceSeries實例。這是標準的OO,不應該需要任何元編程。 – silvabox 2015-02-11 07:53:40