5

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.

4
  • 2
    looks fine to me, although the hash_from_array variable naming is a little bit of overkill. "h" would probably do it. Commented Feb 10, 2010 at 17:33
  • heh, was mealy to improve the readability of the example. :) Commented Feb 10, 2010 at 19:14
  • 1
    a very direct solution - I like it Commented Feb 11, 2010 at 15:58
  • don't forget to compact the final array (result) :) Commented Feb 27, 2010 at 7:33

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.