convert hash to object

后端 未结 6 795
小蘑菇
小蘑菇 2021-02-07 03:06

I am trying to convert hash and nested hashes to objects.

so far first hash object is converted successfully by this code:

class Hashit
  def initialize(         


        
6条回答
  •  半阙折子戏
    2021-02-07 03:47

    If I understand the question correctly, this should do it:

    class Hashit
      def initialize(hash)
        convert_to_obj(hash)
      end
    
      private
    
      def convert_to_obj(h)
        h.each do |k,v|
          self.class.send(:attr_accessor, k)
          instance_variable_set("@#{k}", v) 
          convert_to_obj(v) if v.is_a? Hash
        end
      end
    end
    
    h = Hashit.new( { a: '123r',
          b: { c: 'sdvs', d: { e: { f: 'cat' }, g: {h: 'dog'} } } })
      #=> #"sdvs", :d=>{:e=>{:f=>"cat"}, :g=>{:h=>"dog"}}},
      #       @c="sdvs", @d={:e=>{:f=>"cat"}, :g=>{:h=>"dog"}},
      #       @e={:f=>"cat"}, @f="cat", @g={:h=>"dog"}, @h="dog">
    h.instance_variables
      #=> [:@a, :@b, :@c, :@d, :@e, :@f, :@g, :@h]
    Hashit.instance_methods(false)
      #=> [:a, :a=, :b, :b=, :c, :c=, :d, :d=, :e, :e=, :f, :f=, :g, :g=, :h, :h=]
    h.d
      #=> {:e=>{:f=>"cat"}}
    h.d = "cat"
    h.d
      #=> "cat"
    

提交回复
热议问题