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

instantiating a composite class from an instance method Ruby

在周末开始编写代码之前,我正在研究在 Ruby 中强制执行 class 关系的方法。我正在尝试建立一种复合关系,但我可以从 Commodity class.

外部对 PriceSeries class 进行某种程度的控制

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

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)

你能解释一下 'enforcing class relationships in Ruby' 和 'a composite relationship' 是什么意思吗?

在 Ruby 中的另一个 class 中定义一个 class,正如您在示例中所做的那样,不会赋予任何一个 class 相对于另一个的特权,它简单命名空间 'inner' class。即 PriceSeries(在 Commodity 之外引用时)将是 Commodity::PriceSeries.

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