从实例方法Ruby实例化复合类

时间:2015-02-10 19:59:17

标签: ruby instantiation composite

在我开始在周末编写代码之前,我正在玩Ruby中强制类关系的方法。我正在尝试复合关系,但是我可以从Commodity类之外控制PriceSeries类。

显然这不是,但是有理由设置这样的设置吗?我是否认为这会产生私有数据并且可能适合存储用户实例的密码(例如)?

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)

1 个答案:

答案 0 :(得分:0)

你能解释一下你在Ruby中强制执行类关系的意思吗?和'复合关系'?

在Ruby中的另一个类中定义一个类,就像你在示例中所做的那样,并没有给出任何一个类的特殊权限,它只是将内部命名为' inner'类。即PriceSeries(在Commodity之外引用时)为Commodity::PriceSeries

这与在C#和Java等语言中定义内部类不同。

相关问题