开发者

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

开发者 https://www.devze.com 2023-01-18 08:25 出处:网络
for example: [ (id=>1, email=>\'tim@tim.com\',开发者_运维问答 name=>\'tim\'), (id=>2, email=>\'joe@joe.com\', name=>\'joe\'),

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. 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.


[ {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']}
0

精彩评论

暂无评论...
验证码 换一张
取 消