Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving specific hash key values from an array of hashes

All,

I was wondering if anyone knew a better patten than:

array_of_hashes.map { |hash_from_array| hash_from_array[:key] }

for retrieving an array of values with a specific key from an array of hashes containing that key.

like image 706
Roja Buck Avatar asked Nov 15 '22 12:11

Roja Buck


1 Answers

From the Ruby code perspective, the map is pretty elegant and straightforward.

From the algorithmic point of view (to address the computer-science tag), it seems a solution to this problem cannot be better than going through the whole array once (i.e. a map here), so it will take as much time as to process each hash in the array.

@Vlad: Compacting the returned array depends on what will be done with the array, right? :-)

like image 158
Eric Platon Avatar answered Dec 09 '22 14:12

Eric Platon