Convert an object to a hash of values ​​in Ruby

I searched around, but cannot find any built-in way to convert an object (my own creation) into a hash of values, so I need to look elsewhere.

My thought was to use .instance_variables, separate @from the front of each variable, and then use attr_accessorfor each to create a hash.

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

+5
source share
5 answers

Assuming all the data you want to include 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} 
+3
source

, , , - , , . .

Object.instance_variables , .

+1

object.instance_values ​​

+1

? ?

Cody Caughlan, . [] . - .

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

, <object>.attributes

a hash.

.

!

-1

All Articles