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.
用于从包含该键的哈希数组中使用特定键检索值数组。
1 个解决方案
#1
1
From the Ruby code perspective, the map
is pretty elegant and straightforward.
从Ruby代码的角度来看,地图非常优雅和简单。
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? :-)
@Vlad:压缩返回的数组取决于对数组的处理方式,对吧? :-)
#1
1
From the Ruby code perspective, the map
is pretty elegant and straightforward.
从Ruby代码的角度来看,地图非常优雅和简单。
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? :-)
@Vlad:压缩返回的数组取决于对数组的处理方式,对吧? :-)