简体   繁体   English

我将如何分解并从Ruby on Rails中的哈希数组中提取数组?

[英]How would I break up and extract an array from an array-of-hashes in Ruby on Rails?

for example: 例如:

[ (id=>1, email=>'tim@tim.com', name=>'tim'),
  (id=>2, email=>'joe@joe.com', name=>'joe'),
  (id=>3, email=>'dan@dan.com', name=>'dan') ]

How can I extract the email column and put it in its own array? 如何提取电子邮件列并将其放入自己的数组中?

Let's call your array users . 我们打电话给你的阵列users You can do this: 你可以这样做:

users.map{|u| u[:email]}

This looks at the hashes one by one, calling them u , extracts the :email key, and returns the results in a new array of user emails. 这将逐个查看哈希值,将它们称为u ,提取:email键,然后在新的用户电子邮件数组中返回结果。

[ {id=>1, email=>'tim@tim.com', name=>'tim'},
  {id=>2, email=>'joe@joe.com', name=>'joe'},
  {id=>3, email=>'dan@dan.com', name=>'dan'} ].map{|h| h['email']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM