Array and Hash ... how to find the value ? DRYest way

I have an array of hash : tags_on => [{:point=>["a", "b", "c"]}, {:comma=>["d", "e"]}]

and I would like to get the value ["d", "e"] for a specified key :comma is there any DRY way to do it or should I loop into the array ?

thanks for your feedback

What if your array of hashes looks like this:

  [{:point=>["a", "b", "c"], :comma=>["f", "g"]}, {:comma=>["d", "e"]}] would you know which :comma key to retrieve?

Assuming the keys are unique why don't you build it as a straight hash in the first place? If they are not unique then you are in trouble anyway. If you are stuck with the array then I think I would use collect to convert it into a straight hash first.


they wil be unique , before adding a new hash, I'll have to check if the key already exist but I agree with Colin, better build a straight hash first

you're right, rather than pushing hash into tags_on , I'll have to build it as a straight hash

That's kindof what I was getting at - if the keys are unique, you don't have an array of hashes, you have a hash! :slight_smile:

For reference, this will do what you're looking for (array starts in tags_on, key in desired_key):

hash = tags_on.detect { |h| h.has_key?(desired_key) } result = hash[desired_key] if hash

I've had to build little arrays of single-key hashes like this to work around 1.8.6 not having ordered hash semantics.

--Matt Jones

...or you have a normal hash with one of the values as an array of the keys in the order you want (I normally call it ":order"). Then when you want to iterate you hash in order:

my_hash = {:name => "fred", :order => [:age, :foo, :name], :age => "21", :foo => "bar"} my_hash[:order].each do |key|   puts my_hash[key] end

Keeps it all "standard" and in one object... YMMV