What is a Ruby analogue of Python variables undeclared in a class definition?

I can store any number of variables not declared in the class definition in an instance of the class in Python.

How can I do something like this in Ruby?

class C: pass a = C() b = C() aa = 1 ab = 2 b.test1 = 11 print aa, ab, b.test1 
+4
source share
2 answers
 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> 
+2
source

If in your case there is more use than is presented, this seems like a good place to use OpenStruct :

 require 'ostruct' a = OpenStruct.new b = OpenStruct.new aa = 1 ab = 2 b.test1 = 11 [aa, ab, 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 aa = 1 ab = 2 b.test1 = 11 [aa, ab, b.test1] # => [1, 2, 11] 

None of the ways you use OpenStruct is an exact parallel to your Python code, but one or the other will probably do everything you need in a cleaner way than instance_variable_set if you don't need it.

+7
source

Source: https://habr.com/ru/post/1484326/


All Articles