Ruby 将对象转换为哈希
假设我有一个 Gift
对象,其中 @name = "book"
& @价格 = 15.95
。将其转换为 Ruby 中的哈希 {name: "book", Price: 15.95}
的最佳方法是什么,而不是 Rails(尽管也可以随意给出 Rails 答案)?
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 {name: "book", price: 15.95}
in Ruby, not Rails (although feel free to give the Rails answer too)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
只是说(当前对象)
.attributes
.attributes
返回任何对象
的哈希
。而且它也干净得多。Just say (current object)
.attributes
.attributes
returns ahash
of anyobject
. And it's much cleaner too.或者使用
each_with_object
:Alternatively with
each_with_object
:实施
#to_hash
?Implement
#to_hash
?您可以使用
as_json
方法。它将把你的对象转换成哈希值。但是,该哈希值将作为该对象名称的值作为键。在您的情况下,
如果您需要存储在对象中的哈希,请使用
as_json(root: false)
。我认为默认情况下 root 将是 false。有关更多信息,请参阅官方 ruby 指南http://api. rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json
You can use
as_json
method. It'll convert your object into hash.But, that hash will come as a value to the name of that object as a key. In your case,
If you need a hash that's stored in the object use
as_json(root: false)
. I think by default root will be false. For more info refer official ruby guidehttp://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json
对于 Active Record 对象
,然后只需调用
For Active Record Objects
and then just call
如果您不在 Rails 环境中(即没有可用的 ActiveRecord),这可能会有所帮助:
If you are not in an Rails environment (ie. don't have ActiveRecord available), this may be helpful:
您可以使用函数式风格编写非常优雅的解决方案。
You can write a very elegant solution using a functional style.
使用“hashable”gem 递归地将对象转换为哈希值 (https://rubygems.org/gems/hashable )
示例
Recursively convert your objects to hash using 'hashable' gem (https://rubygems.org/gems/hashable)
Example
您应该重写对象的
inspect
方法以返回所需的哈希值,或者仅实现类似的方法而不重写默认的对象行为。如果您想要更高级,可以使用 object.instance_variables
You should override the
inspect
method of your object to return the desired hash, or just implement a similar method without overriding the default object behaviour.If you want to get fancier, you can iterate over an object's instance variables with object.instance_variables
可能想尝试
instance_values
。这对我有用。Might want to try
instance_values
. That worked for me.抄袭@Mr. L 在上面的评论中,尝试
@gift.attributes.to_options
。To plagiarize @Mr. L in a comment above, try
@gift.attributes.to_options
.您可以使用
symbolize_keys
,如果您有嵌套属性,我们可以使用deep_symbolize_keys
:You can use
symbolize_keys
and in-case you have nested attributes we can usedeep_symbolize_keys
:生成浅表副本作为模型属性的哈希对象
检查结果对象的类型
Produces a shallow copy as a hash object of just the model attributes
Check the type of the resulting object
如果您还需要转换嵌套对象。
If you need nested objects to be converted as well.
Gift.new.attributes.symbolize_keys
Gift.new.attributes.symbolize_keys
要在不使用 Rails 的情况下执行此操作,一种简洁的方法是将属性存储在常量中。
然后,要将
Gift
实例转换为Hash
,您可以:这是一个很好的方法,因为它只包含您在
上定义的内容attr_accessor
,而不是每个实例变量。To do this without Rails, a clean way is to store attributes on a constant.
And then, to convert an instance of
Gift
to aHash
, you can:This is a good way to do this because it will only include what you define on
attr_accessor
, and not every instance variable.我开始使用结构来轻松进行哈希转换。
我没有使用裸结构,而是创建了自己的从哈希派生的类,这允许您创建自己的函数,并且它记录了类的属性。
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.
按照我无法编译的 Nate 答案:
选项 1
然后你这样称呼它:
选项 2
然后你这样称呼它:
Following Nate's answer which I haven't been able to compile:
Option 1
And then you call it like that:
Option 2
And then you call it like that: