我想在我的類中使用結構來節省記憶體,但我希望我的代碼可以被其他人輕松使用。
假設我想使用一個新的 Struct,將其命名為“KE”。我希望這個 Struct 只能在 I 類中可見,那就是使用它。即,如果使用我的代碼的任何人在其他地方定義了類/結構“KE”,它不會覆寫我的“KE”,而我的也不會覆寫他們的。將它放在同一個代碼文本檔案中也很好。
uj5u.com熱心網友回復:
您可以將代碼放入一個模塊中,該模塊將充當命名空間,例如:
module Foo
KE = Struct.new(:name)
# remaining code
end
在Foo
命名空間中,您可以僅通過 參考結構KE
,例如:
module Foo
# ...
def self.build_ke(name)
KE.new(name)
end
end
Foo.build_ke('abc')
#=> #<struct Foo::KE name="abc">
但是Foo
,您必須使用Foo::
前綴:
Foo::KE.new('def')
#=> #<struct Foo::KE name="def">
其他KE
常數不會干擾您的KE
:
KE = :top_level
module Bar
KE = :nested_in_bar
end
KE #=> :top_level
Bar::KE #=> :nested_in_bar
Foo::KE #=> Foo::KE # <- your struct
要“隱藏”結構,您可以通過以下方式將常量設為私有private_constant
:
module Foo
KE = Struct.new(:name)
private_constant :KE
def self.build_ke(name)
KE.new(name)
end
end
Foo.build_ke #=> #<struct Foo::KE name="abc">
Foo::KE #=> NameError: private constant Foo::KE referenced
或者,您可以通過不首先將其分配給常量來使用匿名結構,例如通過私有類方法:
module Foo
def self.ke_class
@ke_class ||= Struct.new(:name)
end
private_class_method :ke_class
def self.build_ke(name)
ke_class.new(name)
end
end
Foo.build_ke('abc') #=> #<struct name="abc">
Foo.ke_class #=> NoMethodError: private method `ke_class' called for Foo:Module
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489065.html
下一篇:attr_reader不好嗎?