将结构数据作为 ruby​​ 中的哈希返回 [英] returning struct data as a hash in ruby

查看:49
本文介绍了将结构数据作为 ruby​​ 中的哈希返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有将标准 ruby​​ 结构的数据作为散列(成员、值对)返回的方法是否有正当理由?看到结构体和散列具有非常相似的用例,我很惊讶不存在这样的方法.还是我太瞎了?

Is there a valid reason for there not being a method to return the data of a standard ruby struct as a hash (member, value pairs)? Seeing that structs and hashes have very similar use cases, I'm surprised that no such method exists. Or does it, and I'm just too blind?

它很容易实现(我现在已经这样做了),但是标准库中缺乏这样的功能,让我觉得我可能没有真正掌握 ruby​​ 中结构的概念.

It's easy to implement (and i have done so for now), but lack of such functionality in the standard libs, has me thinking that I might have not really grasped the concept of structs in ruby.

推荐答案

(Ruby <= 1.9.3) OpenStructOpenStruct#marshall_dumpStructStruct#each_pair(使用 to_a 获取对和 Hash+to_a 获取哈希值):

(Ruby <= 1.9.3) OpenStruct has OpenStruct#marshall_dump and Struct has Struct#each_pair (use to_a to get the pairs and Hash+to_a to get the hash):

Person = Struct.new(:name, :age)
person = Person.new("Jamie", 23)
person_hash = Hash[person.each_pair.to_a]
#=> {:age=>23, :name=>"Jamie"}

使用 Ruby 2.0 事情变得更容易:Struct#to_hOpenStruct#to_h:

With Ruby 2.0 things are easier: Struct#to_h, OpenStruct#to_h:

Person = Struct.new(:name, :age)
person = Person.new("Jamie", 23)
person_hash = person.to_h
#=> {:age=>23, :name=>"Jamie"}

这篇关于将结构数据作为 ruby​​ 中的哈希返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆