Ruby convert Object to Hash

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

    Implement #to_hash?

    class Gift
      def to_hash
        hash = {}
        instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) }
        hash
      end
    end
    
    
    h = Gift.new("Book", 19).to_hash
    
    0 讨论(0)
  • 2020-12-12 10:58

    Gift.new.attributes.symbolize_keys

    0 讨论(0)
  • 2020-12-12 11:00
    class Gift
      def initialize
        @name = "book"
        @price = 15.95
      end
    end
    
    gift = Gift.new
    hash = {}
    gift.instance_variables.each {|var| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
    p hash # => {"name"=>"book", "price"=>15.95}
    

    Alternatively with each_with_object:

    gift = Gift.new
    hash = gift.instance_variables.each_with_object({}) { |var, hash| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
    p hash # => {"name"=>"book", "price"=>15.95}
    
    0 讨论(0)
  • 2020-12-12 11:01
    Gift.new.instance_values # => {"name"=>"book", "price"=>15.95}
    
    0 讨论(0)
  • 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() 
    
    0 讨论(0)
  • 2020-12-12 11:03
    class Gift
      def to_hash
        instance_variables.map do |var|
          [var[1..-1].to_sym, instance_variable_get(var)]
        end.to_h
      end
    end
    
    0 讨论(0)
提交回复
热议问题