Home > Back-end >  Transfer array of objects to array of only one attribute in ruby
Transfer array of objects to array of only one attribute in ruby

Time:12-19

I am trying to Transfer array of objects to array of only one attribute in ruby. example - I have something like this :

arr = [       
 {
   name: hihihihi,
   phone: null,
   email: [email protected],
   position: null
 },
 {
   name: hi,
   phone: null,
   email: [email protected],
   position: null
 }
]

and i want the output to be:

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

(to make an array (with apostrophe) just form the email attribute)

Thank you

I would like to find out the most efficient way to do so

CodePudding user response:

This is very straightforward with #map once we correct your syntax in defining arr a bit.

arr = [       
 {
   name: 'hihihihi',
   phone: 'null',
   email: '[email protected]',
   position: 'null'
 },
 {
   name: 'hi',
   phone: 'null',
   email: '[email protected]',
   position: 'null'
 }
]

arr.map { |h| h[:email] }
  • Related