Get all instance variables declared in class

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]

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 }]

Tags:

Ruby