如何在 Ruby 中创建哈希数组
ruby 新手,我正在尝试创建一个哈希数组(或者我是否将其倒退?)
def collection
hash = { "firstname" => "Mark", "lastname" => "Martin", "age" => "24", "gender" => "M" }
array = []
array.push(hash)
@collection = array[0][:firstname]
end
@collection 没有显示位置 0 中对象的名字...我做错了什么?
提前致谢!
New to ruby and I'm trying to create an array of hashes (or do I have it backwards?)
def collection
hash = { "firstname" => "Mark", "lastname" => "Martin", "age" => "24", "gender" => "M" }
array = []
array.push(hash)
@collection = array[0][:firstname]
end
@collection does not show the firstname for the object in position 0... What am I doing wrong?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在使用
Symbol
作为使用String
对象作为键的Hash
对象的索引,因此只需执行以下操作:我鼓励您使用
Symbol
作为Hash
键而不是String
,因为Symbol
被缓存,因此效率更高,所以这将是一个更好的解决方案:You're using a
Symbol
as the index into theHash
object that usesString
objects as keys, so simply do this:I would encourage you to use
Symbol
s asHash
keys rather thanString
s becauseSymbol
s are cached, and therefore more efficient, so this would be a better solution:您已将散列的键定义为
String
。但随后您尝试将其引用为Symbol
。那是行不通的。尝试
You have defined the keys of your hash as
String
. But then you are trying to reference it asSymbol
. That won't work that way.Try
你可以这样做:
You can do this: