Dukeh Dukeh - 1 year ago 70
Ruby Question

Converting an object to a hash of values in Ruby

I have searched around, but can't find any built-in way to do convert an object (of my own creation) to a hash of values, so must needs look elsewhere.

My thought was to use

, strip the
from the front of each variable, and then use the
for each to create the hash.

What do you guys think? Is that the 'Ruby Way', or is there a better way to do this?

Answer Source

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)]

foo = Foo.new
foo.a = 1
foo.b = "Test"
foo.c = Time.now
 => {:b=>"Test", :a=>1, :c=>Fri Jul 09 14:51:47 0200 2010} 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download