From: Kent Dahl Date: 2002-09-27T21:01:59+09:00 Subject: Re: object attributes list William Djaja Tjokroaminata wrote: > class Customer > attr_reader :Customerid, :city > def initialize > @Customerid = 123 > @city = 'abc' > end > end > > c = Customer.new > > hash = {} > c.instance_variables.each do |var| > var = var.slice (1...(var.length)) > val = eval "c.#{var}" > hash[var] = val > end > hash.each_key {|key| puts "\"#{key}\" => \"#{hash[key]}\""} This works wonders as long as 1) all instance variables are exposed with a reader 2) no method has the name of an instance variable and does anything different from returning the variable. I'd be more inclined to do something like this (mercilessly refactored from the above): class Customer attr_reader :Customerid, :city def initialize @Customerid = 123 @city = 'abc' @secret = 'hush hush' end def secret "[confidential]" end end c = Customer.new class Object def instance_variables_to_hash result = {} self.instance_variables.each do |var| result[var] = eval var end result end end hash = c.instance_variables_to_hash hash.each_key {|key| puts "\"#{key}\" => \"#{hash[key]}\""} Not sure this will work too well when we get truely private instance variables (i.e. protected from subclasses... Will they also be protected from superclasses?) -- (\[ Kent Dahl ]/)_ _~_ __[ http://www.stud.ntnu.no/~kentda/ ]___/~ ))\_student_/(( \__d L b__/ NTNU - graduate engineering - 5. year ) ( \__\_�|�_/__/ ) _)Industrial economics and technological management( \____/_�_\____/ (____engineering.discipline_=_Computer::Technology___)