convert hash to object

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

    Ruby has an inbuilt data structure OpenStruct to solve something like this. Still, there is a problem. It is not recursive. So, you can extend OpenStruct class like this:

    # Keep this in lib/open_struct.rb
    class OpenStruct
      def initialize(hash = nil)
        @table = {}
        if hash
          hash.each_pair do |k, v|
            k = k.to_sym
            @table[k] = v.is_a?(Hash) ? OpenStruct.new(v) : v
          end
        end
      end
    
      def method_missing(mid, *args) # :nodoc:
        len = args.length
        if mname = mid[/.*(?==\z)/m]
          if len != 1
            raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
          end
          modifiable?[new_ostruct_member!(mname)] = args[0].is_a?(Hash) ? OpenStruct.new(args[0]) : args[0]
        elsif len == 0 # and /\A[a-z_]\w*\z/ =~ mid #
          if @table.key?(mid)
            new_ostruct_member!(mid) unless frozen?
            @table[mid]
          end
        else
          begin
            super
          rescue NoMethodError => err
            err.backtrace.shift
            raise
          end
        end
      end
    end
    

    and remember to require 'open_struct.rb' next time you want to use OpenStruct.

    Now you can do something like this:

    person = OpenStruct.new
    person.name = "John Smith"
    person.age  = 70
    person.more_info = {interests: ['singing', 'dancing'], tech_skills: ['Ruby', 'C++']}
    
    puts person.more_info.interests
    puts person.more_info.tech_skills
    

提交回复
热议问题