How to get attributes that were defined through attr_reader or attr_accessor

前端 未结 6 1570
温柔的废话
温柔的废话 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:55

    If you have attr_writers/attr_accessors defined on your attributes, than they can be easily retrieved by matching the =$ regexp:

    A.instance_methods.each_with_object([]) { |key, acc| acc << key.to_s.gsub(/=$/, '') if key.match(/\w=$/) }
    

    OR

    A.instance_methods.each_with_object([]) { |key, acc| acc << key if key = key.to_s.match(/^(.*\w)=$/)&.[](1) }
    

提交回复
热议问题