Ruby convert Object to Hash

前端 未结 17 1670
滥情空心
滥情空心 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:17

    Might want to try instance_values. That worked for me.

    0 讨论(0)
  • 2020-12-12 11:17

    Produces a shallow copy as a hash object of just the model attributes

    my_hash_gift = gift.attributes.dup
    

    Check the type of the resulting object

    my_hash_gift.class
    => Hash
    
    0 讨论(0)
  • 2020-12-12 11:17

    I started using structs to make easy to hash conversions. Instead of using a bare struct I create my own class deriving from a hash this allows you to create your own functions and it documents the properties of a class.

    require 'ostruct'
    
    BaseGift = Struct.new(:name, :price)
    class Gift < BaseGift
      def initialize(name, price)
        super(name, price)
      end
      # ... more user defined methods here.
    end
    
    g = Gift.new('pearls', 20)
    g.to_h # returns: {:name=>"pearls", :price=>20}
    
    0 讨论(0)
  • 2020-12-12 11:20

    You can write a very elegant solution using a functional style.

    class Object
      def hashify
        Hash[instance_variables.map { |v| [v.to_s[1..-1].to_sym, instance_variable_get v] }]
      end
    end
    
    0 讨论(0)
  • 2020-12-12 11:21

    If you are not in an Rails environment (ie. don't have ActiveRecord available), this may be helpful:

    JSON.parse( object.to_json )
    
    0 讨论(0)
提交回复
热议问题