convert hash to object

后端 未结 6 734
小蘑菇
小蘑菇 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:48

    You need to add recursivity:

    class Hashit
      def initialize(hash)
        hash.each do |k,v|
          self.instance_variable_set("@#{k}", v.is_a?(Hash) ? Hashit.new(v) : v)
          self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})
          self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})
        end
      end
    end
    
    h = Hashit.new({a: '123r', b: {c: 'sdvs'}})
    # => #>
    

提交回复
热议问题