在Ruby中将类转换为哈希

我正在尝试使用 ruby​​ 将任何类转换为哈希。我所做的初步实现:

class Object
    def to_hash
        instance_variables.map{ |v| 
            Hash[v.to_s.delete("@").to_sym, instance_variable_get(v)] }.inject(:merge)
   end
end

一切似乎都正常。但是当我尝试以下代码时:

class Person
    attr_accessor :name, :pet
    def initialize(name, pet)
       @name = name
       @pet = pet
    end
end

class Pet
    attr_accessor :name, :age 
    def initialize(name, age)
       @name = name
       @age = age
    end
end


tom =  Person.new("Tom", Pet.new("Tobby", 5))
puts tom.to_hash

我有以下输出

{:name=>"Tom", :pet=>#<Pet:0x0055ff94072378 @name="Tobby", @age=5>}

我无法散列 Pet 类型的属性 pet(或任何其他自定义类)

有任何想法吗?

编辑
这就是我希望返回的内容:

{:name=>"Tom", :pet=>{ :name=>"Tobby", :age=>5}}

回答

当您也希望将关联对象作为散列返回时,您必须to_hash递归调用:

class Object
  def to_hash
    return self if instance_variables.empty?

    instance_variables
      .map { |v| [v.to_s.delete("@").to_sym, instance_variable_get(v).to_hash] }
      .to_h
  end
end

tom =  Person.new("Tom", Pet.new("Tobby", 5))
puts tom.to_hash
#=> { :name=>"Tom", :pet => { :name=>"Tobby", :age=>5 } }


以上是在Ruby中将类转换为哈希的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>