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
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.