8

So I know that you can get all instance variables in Ruby by calling #instance_variables, but if they haven't yet been set then they don't show up.

Example

class Walrus
  attr_accessor :flippers, :tusks
end

w = Walrus.new
w.instance_variables # => []
w.tusks              # => nil
w.instance_variables # => [:@tusks]

I want to access all of the instance variables defined by attr_accessor immediately.

w = Walrus.new
w.instance_variables # => [:@tusks, :@flippers]
Chris
  • 11,819
  • 19
  • 91
  • 145
  • possible duplicate of [How to get attributes that were defined through attr\_reader or attr\_accessor](http://stackoverflow.com/questions/10006889/how-to-get-attributes-that-were-defined-through-attr-reader-or-attr-accessor) – Aidan Feldman Dec 04 '14 at 22:01

3 Answers3

15

Well, they don't yet exist. Instance variables spring into existence upon first assignment. If you want them in a brand new instance, then touch them in the constructor.

class Walrus
  attr_accessor :flippers, :tusks

  def initialize
    self.flippers = self.tusks = nil
  end
end

w = Walrus.new
w.instance_variables # => [:@tusks, :@flippers]
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
5

Well, attr_accessor creates a pair of methods, a setter and a getter. I'm not sure if there's a built-in way to get a list, but you could look through the instance methods for the resulting pairs:

Walrus.instance_methods.find_all do |method|
  method != :== &&
  method != :! &&
  Walrus.instance_methods.include?(:"#{method}=")
end
Rob Davis
  • 15,597
  • 5
  • 45
  • 49
0

How about using methods minus the methods from Object or Class? the returning array will contain your defined attributes/methods, and the instance variables defined in getter/accessor.

your_instance_name.methods - Object.methods
your_instance_name.methods - Class.methods
xjlin0
  • 341
  • 5
  • 10