我可以在Python类的类实例中将未定义的任何变量存储在类定义中。
我如何在Ruby中做这样的事情?
class C:
pass
a = C()
b = C()
a.a = 1
a.b = 2
b.test1 = 11
print a.a, a.b, b.test1
答案 0 :(得分:7)
除非您的用例多于呈现的内容,否则这似乎是使用OpenStruct的好地方:
require 'ostruct'
a = OpenStruct.new
b = OpenStruct.new
a.a = 1
a.b = 2
b.test1 = 11
[a.a, a.b, b.test1]
# => [1, 2, 11]
根据您的使用情况,您可能更愿意:
require 'ostruct'
class C < OpenStruct
# You may want stuff in here...
end
a = C.new
b = C.new
a.a = 1
a.b = 2
b.test1 = 11
[a.a, a.b, b.test1]
# => [1, 2, 11]
使用OpenStruct的方式与Python代码完全并行,但如果您不严格需要,那么其中一个或多个似乎可能以比instance_variable_set
更清晰的方式执行您想要的任何操作。
答案 1 :(得分:2)
irb(main):001:0> class C
irb(main):002:1> end
=> nil
irb(main):003:0> a = C.new
=> #<C:0xb73aac70>
irb(main):004:0> b = C.new
=> #<C:0xb73a5838>
irb(main):005:0> a.instance_variable_set(:@a, 1)
=> 1
irb(main):006:0> a.instance_variable_set(:@b, 2)
=> 2
irb(main):007:0> b.instance_variable_set(:@test1, 11)
=> 11
irb(main):008:0> a
=> #<C:0xb73aac70 @b=2, @a=1>
irb(main):009:0> b
=> #<C:0xb73a5838 @test1=11>