How to get attributes that were defined through attr_reader or attr_accessor

前端 未结 6 1577
温柔的废话
温柔的废话 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 06:05

    While Sergio's answer helps, it will return all the instance variables, which if I understand correctly the OP's question, is not what is asked.

    If you want to return only the 'attributes' that have e.g. a mutator, you have to do something slightly more complicated such as:

    attrs = Hash.new
    instance_variables.each do |var|
      str = var.to_s.gsub /^@/, ''
      if respond_to? "#{str}="
        attrs[str.to_sym] = instance_variable_get var
      end
    end
    attrs
    

    This returns only the attributes declared with attr_accessor (or with a manually created mutator), and keep the internal instance variables hidden. You can do something similar if you want the ones declared with attr_reader.

提交回复
热议问题