We have a class with attr_accessor
s. Such as:
class Class
attr_accessor :x
attr_accessor :y
...
end
I want to create a hash from an instance of this class. Such as:
c.to_attr_hash = { :x => "x", :y => "y" }
How could this be done?
We have a class with attr_accessor
s. Such as:
class Class
attr_accessor :x
attr_accessor :y
...
end
I want to create a hash from an instance of this class. Such as:
c.to_attr_hash = { :x => "x", :y => "y" }
How could this be done?
class Class
attr_accessor :x
attr_accessor :y
def to_attr_hash
hash = Hash.new
instance_variables.each do |v|
hash[v] = instance_variable_get(v)
end
hash
end
end
c = Class.new
c.x = 'a'
c.y = 'b'
p c.to_attr_hash
#=> {:@x=>"a", :@y=>"b"}