我已经四处搜索,但找不到任何内置的方法来将对象(我自己创建的)转换为值的哈希值,因此必须寻找其他地方.
我的想法是使用.instance_variables
,@
从每个变量的前面剥离,然后使用attr_accessor
for each创建哈希.
你们有什么感想?这是'Ruby Way',还是有更好的方法来做到这一点?
假设您想要包含在哈希中的所有数据都存储在实例变量中:
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}
Run Code Online (Sandbox Code Playgroud)