Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Rubyish Way To Get An Array Containing Specific Values From An Array Of Objects?

Tags:

arrays

ruby

I have an array of ruby objects that looks something like this:

[#<email: "someemail" other_properties: "SDFDF">, #<...>, #<...>]

Each of the objects in the array has an email property. I want to get a new array of all the email properties of the ruby objects in the array.

After executing the code, I would have an array that looked like this:

["[email protected]", "[email protected]", ...] 

I am newer to ruby and want to do this in the most rubyish way possible.

My question is, what's the best way to do this in ruby?

like image 653
Alex Avatar asked Apr 18 '11 20:04

Alex


1 Answers

You can use the map method to apply a block to each element of the array, returning a new array containing the results of each invocation:

somearray.map {|x| x.email}
like image 192
Brian Campbell Avatar answered Oct 08 '22 14:10

Brian Campbell