简体   繁体   中英

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]

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM