Ruby convert Object to Hash

前端 未结 17 1691
滥情空心
滥情空心 2020-12-12 10:35

Let\'s say I have a Gift object with @name = \"book\" & @price = 15.95. What\'s the best way to convert that to the Hash {na

17条回答
  •  无人及你
    2020-12-12 11:07

    If you need nested objects to be converted as well.

    # @fn       to_hash obj {{{
    # @brief    Convert object to hash
    #
    # @return   [Hash] Hash representing converted object
    #
    def to_hash obj
      Hash[obj.instance_variables.map { |key|
        variable = obj.instance_variable_get key
        [key.to_s[1..-1].to_sym,
          if variable.respond_to? <:some_method> then
            hashify variable
          else
            variable
          end
        ]
      }]
    end # }}}
    

提交回复
热议问题