创建红宝石哈希数组 [英] Creating array of hashes in ruby

查看:232
本文介绍了创建红宝石哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建散列红宝石中的一个数组:

I want to create an array of hashes in ruby as:

 arr[0]
     "name": abc
     "mobile_num" :9898989898
     "email" :abc@xyz.com

 arr[1]
     "name": xyz
     "mobile_num" :9698989898
     "email" :abcd@xyz.com

我见过哈希并的阵列文档。总之,我发现,我必须做些什么

I have seen hash and array documentation. In all I found, I have to do something like

c = {}
c["name"] = "abc"
c["mobile_num"] = 9898989898
c["email"] = "abc@xyz.com"

arr << c

作为迭代在循环上述声明让我填写改编。其实我有一排像 rowofrows [ABC,9898989898,abc@xyz.com] 。有没有更好的方式来做到这一点?

Iterating as in above statements in loop allows me to fill arr. I actually rowofrows with one row like ["abc",9898989898,"abc@xyz.com"]. Is there any better way to do this?

推荐答案

假设你的rowofrows的意思是数组的数组,继承人的解决方案是什么,我认为你要做到:

Assuming what you mean by "rowofrows" is an array of arrays, heres a solution to what I think you're trying to accomplish:

array_of_arrays = [["abc",9898989898,"abc@xyz.com"], ["def",9898989898,"def@xyz.com"]]

array_of_hashes = []
array_of_arrays.each { |record| array_of_hashes << {'name' => record[0], 'number' => record[1].to_i, 'email' => record[2]} }

p array_of_hashes

将输出您的哈希值的数组:

Will output your array of hashes:

[{"name"=>"abc", "number"=>9898989898, "email"=>"abc@xyz.com"}, {"name"=>"def", "number"=>9898989898, "email"=>"def@xyz.com"}]

这篇关于创建红宝石哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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