Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get attr_accessor/instance variables in ruby

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]
like image 753
Chris Avatar asked May 18 '12 14:05

Chris


2 Answers

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]
like image 92
Sergio Tulentsev Avatar answered Sep 24 '22 15:09

Sergio Tulentsev


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
like image 37
Rob Davis Avatar answered Sep 22 '22 15:09

Rob Davis