当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby - 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.

网友答案:

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? :-)

分享给朋友:
您可能感兴趣的文章:
随机阅读: