convert hash to object

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

    You could check the type on v when you initialize the object and call new to get a new Hashit when it is a another hash.

    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
    

    and the resulting snippet from before would be:

    h = Hashit.new({a: '123r', b: {c: 'sdvs'}})
    => #>
    

提交回复
热议问题