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]
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With