Get attr_accessor/instance variables in ruby

Chris picture Chris · May 18, 2012 · Viewed 9.2k times · Source

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]

Answer

Sergio Tulentsev picture Sergio Tulentsev · May 18, 2012

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]