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
. 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']}
精彩评论