简体   繁体   中英

Better way to search array in Ruby?

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?

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"]

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM