Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Ruby's analogue of Python's variables, undeclared in the class definition?

Tags:

python

ruby

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
like image 606
user1887348 Avatar asked Jun 04 '13 03:06

user1887348


2 Answers

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.

like image 108
Darshan Rivka Whittle Avatar answered Sep 28 '22 17:09

Darshan Rivka Whittle


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>
like image 43
John La Rooy Avatar answered Sep 28 '22 17:09

John La Rooy