Most Rubyish way to get an array containing specific values ​​from an array of objects?

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

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

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

After executing the code, I will have an array that looks like this:

 [" email@example.com ", " anotheremail@gmail.com ", ...] 

I am new to ruby ​​and want to do it in the most rude way.

My question is: what is the best way to do this in ruby?

+6
source share
1 answer

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 call:

 somearray.map {|x| x.email} 
+16
source

Source: https://habr.com/ru/post/886179/


All Articles