Tim
Tim

Reputation: 1461

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

for example:

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

How can I extract the email column and put it in its own array?

Upvotes: 7

Views: 2179

Answers (2)

shingara
shingara

Reputation: 46904

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

Upvotes: 3

Peter
Peter

Reputation: 132157

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.

Upvotes: 16

Related Questions