I can store any number of variables undeclared in the class definition in a class instance in Python.
How can I do something like this in Ruby?
class C:
pass
a = C()
b = C()
a.a = 1
a.b = 2
b.test1 = 11
print a.a, a.b, b.test1
Unless there's more to your use-case than presented, this seems like a good place to use an 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]
Depending on your use-case, you may prefer:
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]
Neither way of using OpenStruct is an exact parallel of your Python code, but one or the other seems likely to do everything you want in a cleaner way than instance_variable_set
if you don't strictly need it.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With