How to get attributes that were defined through attr_reader or attr_accessor

前端 未结 6 1583
温柔的废话
温柔的废话 2020-12-15 05:10

Suppose I have a class A

class A
  attr_accessor :x, :y

  def initialize(x,y)
    @x, @y = x, y
  end
end

How can I get

6条回答
  •  醉酒成梦
    2020-12-15 05:52

    when you use attr_accessor to define attributes in a class, Ruby using refexion, define a couple of methods, for each attribute declared, one to get the value and other to set, an instance variable of the same name of the attribute

    you can see this methods using

    p A.instance_methods
    
    [:x, :x=, :y, :y=, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?,..
    

    So this attributes are accesible, outside the class, with

    p "#{a.x},#{a.y}"
    

    or inside the class through the corresponding instance variable

    class A
      ...
      def attributes
        [@x,@y]
      end
      ...
    end
    p a.attributes   #=> [5,10]
    

提交回复
热议问题