Converting an object to a hash of values in Ruby?

Assuming all data you want to be included in the hash is stored in instance variables: class Foo attr_writer :a, :b, :c def to_hash Hash*instance_variables. Map { |v| v. To_sym, instance_variable_get(v) }.

Flatten end end foo = Foo. New foo. A = 1 foo.

B = "Test" foo. C = Time. Now foo.

To_hash => {:b=>"Test", :a=>1, :c=>Fri Jul 09 14:51:47 0200 2010}.

In the end I went with a simpler version of this (without the . Map). – Dukeh Jul 20 '10 at 22:02.

I don't know of a native way to do this, but I think your idea of basically just iterating over all instance variables and building up a hash is basically the way to go. Its pretty straight-forward. You can use Object.

Instance_variables to get an Array of all instance variables which you then loop over to get their values.

1 Agreed and if it is something you needed to do more than once, you could just extend Class with a to_hash method. – Geoff Lanotte Jul 9 '10 at 3:15.

If you need a has Geoff Lanotte's suggestion in Cody Caughlan's answer is nice. Otherwise you could overload for your class. Something like.

Class Test def initialize v1, v2, v3 @a = x @b = y @c = z end def x instance_variable_get("@" + x) end end n = Test. New(1, 2, 3) p n:b.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions