Ruby convert Object to Hash

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

    For Active Record Objects

    module  ActiveRecordExtension
      def to_hash
        hash = {}; self.attributes.each { |k,v| hash[k] = v }
        return hash
      end
    end
    
    class Gift < ActiveRecord::Base
      include ActiveRecordExtension
      ....
    end
    
    class Purchase < ActiveRecord::Base
      include ActiveRecordExtension
      ....
    end
    

    and then just call

    gift.to_hash()
    purch.to_hash() 
    

提交回复
热议问题