Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all instance variables declared in class

Tags:

ruby

Please help me get all instance variables declared in a class the same way instance_methods shows me all methods available in a class.

class A   attr_accessor :ab, :ac end  puts A.instance_methods  #gives ab and ac  puts A.something         #gives me @ab @ac... 
like image 265
Akshay Vishnoi Avatar asked Aug 12 '12 21:08

Akshay Vishnoi


People also ask

Where are instance variables declared in a class?

Instance variables are declared at the same level as methods within a class definition. They are usually given private access to restrict visibility. They can receive initial values either when they are declared or in a constructor. Instances variable references may or may not be prefixed with the reserved word this.

How do I get all the instance variables of a Python object?

There are two ways to access the instance variable of class: Within the class by using self and object reference. Using getattr() method.

Can we access instance variable in class method Python?

Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls . Static methods don't have access to cls or self . They work like regular functions but belong to the class's namespace.


2 Answers

You can use instance_variables:

A.instance_variables 

but that’s probably not what you want, since that gets the instance variables in the class A, not an instance of that class. So you probably want:

a = A.new a.instance_variables 

But note that just calling attr_accessor doesn’t define any instance variables (it just defines methods), so there won’t be any in the instance until you set them explicitly.

a = A.new a.instance_variables #=> [] a.ab = 'foo' a.instance_variables #=> [:@ab] 
like image 58
Andrew Marshall Avatar answered Sep 21 '22 19:09

Andrew Marshall


If you want to get all instances variables values you can try something like this :

class A   attr_accessor :foo, :bar    def context     self.instance_variables.map do |attribute|       { attribute => self.instance_variable_get(attribute) }     end   end end  a = A.new a.foo = "foo" a.bar = 42 a.context #=> [{ :@foo => "foo" }, { :@bar => 42 }] 
like image 27
Aschen Avatar answered Sep 20 '22 19:09

Aschen