Ruby将Object转换为Hash

问题描述 投票:111回答:16

假设我有Gift@name = "book"@price = 15.95对象。将它转换为Ruby中的Hash {name: "book", price: 15.95}的最佳方法是什么,而不是Rails(虽然也可以自由地给出Rails的答案)?

ruby object hashmap instance-variables
16个回答
76
投票
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}

或者与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}

4
投票

您应该覆盖对象的inspect方法以返回所需的哈希,或者只是实现类似的方法而不覆盖默认对象行为。

如果你想变得更漂亮,你可以使用object.instance_variables迭代对象的实例变量


4
投票

使用'hashable'gem(https://rubygems.org/gems/hashable)示例递归地将对象转换为哈希值

class A
  include Hashable
  attr_accessor :blist
  def initialize
    @blist = [ B.new(1), { 'b' => B.new(2) } ]
  end
end

class B
  include Hashable
  attr_accessor :id
  def initialize(id); @id = id; end
end

a = A.new
a.to_dh # or a.to_deep_hash
# {:blist=>[{:id=>1}, {"b"=>{:id=>2}}]}

4
投票

可能想尝试instance_values。这对我有用。


1
投票

生成浅拷贝作为模型属性的哈希对象

my_hash_gift = gift.attributes.dup

检查生成的对象的类型

my_hash_gift.class
=> Hash

0
投票

你应该尝试Hashie,一个很棒的宝石:https://github.com/intridea/hashie


0
投票

如果您还需要转换嵌套对象。

# @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 # }}}

0
投票

Gift.new.attributes.symbolize_keys


278
投票

只说(当前对象).attributes

.attributes返回任何hashobject。而且它也更清洁。


46
投票

实施#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

38
投票
Gift.new.instance_values # => {"name"=>"book", "price"=>15.95}

13
投票

对于活动记录对象

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

然后打电话

gift.to_hash()
purch.to_hash() 

11
投票
class Gift
  def to_hash
    instance_variables.map do |var|
      [var[1..-1].to_sym, instance_variable_get(var)]
    end.to_h
  end
end

11
投票

你可以使用as_json方法。它会将您的对象转换为哈希值。

但是,该哈希值将作为该对象名称的值作为键。在你的情况下,

{'gift' => {'name' => 'book', 'price' => 15.95 }}

如果您需要存储在对象中的哈希值,请使用as_json(root: false)。我认为默认情况下root将是false。有关更多信息,请参阅官方红宝石指南

http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json


10
投票

如果您不在Rails环境中(即没有ActiveRecord可用),这可能会有所帮助:

JSON.parse( object.to_json )

6
投票

您可以使用功能样式编写非常优雅的解决方案。

class Object
  def hashify
    Hash[instance_variables.map { |v| [v.to_s[1..-1].to_sym, instance_variable_get v] }]
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.