From: Ne Scripter Date: 2009-09-30T02:40:24+09:00 Subject: Re: Group by unique entries of a hash So if we were to take this further.We now have out hashMapping list "2efa4ba470", "00000005""00000004" "c0784b5de101", "00000006""00000003" "02adecfd5c", "00000002" "c0784b5de101", "00000001" Now we split the hash to give only the ID values (column 2) again doing some like this: hashMapping.each do |itemDetail| newID = itemDetail[1].to_s.delete("\"").strip end I have another declared array in my code, with many more ID values like those shown above moreIDs = ["00000001", "00000003", "00000004", "00000005", 00000007", "00000008"] What I want to is search for all newID's that match moreIDs and output the matching ID and the corresponding code shown in column one. So the sample output would be like this: "2efa4ba470", "00000005""00000004" "c0784b5de101", "00000003" "c0784b5de101", "00000001" Show this shows the string code for an ID that is present in both of my lists. I had thought something like moreID == newID but that creates a lot off do loops. Also, thr though of array intersects crossed my mind, but we have a hash and array hear so I was unsure of how to make this work? Any assistance in greatly appreciated. Ne Scripter wrote: > Ah yes, that makes perfect sense. > > Thanks > > Paul Smith wrote: > >> >> You want a hash where the key is the element you want to group on, and >> the 'item' is an array of all items with the shared key. A bit like >> (untested): >> >> hashMapping = {} >> >> IO.foreach(source.to_s) do |data| >> fields = data.split(",") >> hash = fields[0] >> ocrID = fields[1] >> >> hashMapping[ocrID] ||= [] #If hashMapping has never seen this key >> before, make an empty array >> >> hashMapping[ocrID] << hash #Add the new element to the array for this >> key >> >> end >> >>> >>> Many thanks >>> -- >>> Posted via http://www.ruby-forum.com/. >>> >>> > >> -- >> Paul Smith >> http://www.nomadicfun.co.uk >> >> paul@pollyandpaul.co.uk -- Posted via http://www.ruby-forum.com/.