1

I have an array of hashes:

arr = [{"id"=>"1", "name"=>"Alan"}, {"id"=>"2", "name"=>"Ben"}, {"id"=>"3", "name"=>"Carl"}, {"id"=>"4", "name"=>"Danny"}, {"id"=>"5", "name"=>"Eva"}] 

If I were to find the name of id #4:

arr.find{ |a| a["id"] == "4" }["name"] 

returns "Danny", which is what I want.

My question is, is there a shorter, more elegant way of accomplish the same search?

2
  • 8
    What's not elegant about this? Perfectly readable code, nothing unnecessary. Commented Jun 25, 2015 at 1:00
  • Echoing Sergio -- this is as best as I can think of to do this. Commented Jun 25, 2015 at 1:09

2 Answers 2

4

If you only need to look up one id, a linear search as you are doing is fine.

If you are doing many lookups on the same array, create a hash from the array, so the individual lookups are O(1)

h = Hash[arr.map{|a|[a["id"], a["name"]]}] h["4"] 
Sign up to request clarification or add additional context in comments.

Comments

0

It is a perfectly reasonable way of doing it. The only problem I see is that your data structure is not lookup friendly. You need to search in array, instead of looking up by ID in hash. Searching in array is O(N) and is relatively more difficult code. Looking up in hash is O(1) and is no code at all.

So, I would convert your array to hash, and then look up in it. Especially, if you are planning to do many lookups.

people = arr.inject({}) {|memo,v| memo[v["id"].to_i]=v["name"]; memo} people[4] # will return Danny people[3] # will return Carl 

Hope it helps!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.