From: Thomas Le Date: 2011-10-07T04:58:23+09:00 Subject: Re: comparing elements in same array --90e6ba6e853226f4ac04aea6bfd5 Content-Type: text/plain; charset=ISO-8859-1 This works for me beautifully ... my code looks like this .. still more to go to complete my task but I've passed the first hurdle. #---start code require 'roo' ORGFILE = 'organize.xlsx' xcel = Excelx.new(ORGFILE) xcel.default_sheet = xcel.sheets.first startingRow = 2 nameArray = [] startingRow.upto(xcel.last_row) do |row| name = xcel.cell(row,'A') location = xcel.cell(row,'B') nameArray << [name,location] startingRow += 1 end nameHash = Hash.new nameArray.each { |entry| unless nameHash.has_key?(entry[0]) nameHash[entry[0]] = [entry[1]] else nameHash[entry[0]] << entry[1] end } # --end code Thanks to Jake & Botp. I've learned a lot from your suggestions. TL On Thu, Oct 6, 2011 at 9:28 AM, jake kaiden wrote: > hi Thomas, > > well, if i understand correctly what you want to do, i think this... > > > > nameProfile["#{name}"] = "#{location}" > > > ...is going to be a problem. if the names repeat, the location will > be overwritten each time the name is found, and you'll wind up with only > the last one found as the value for your 'name' key. > > i might instead first set up an array of arrays with your names and > locations, so that you can account for the same name being in multiple > locations. then i would step through the array and create a hash in > which each name was a key, and the value was an array of the locations > associated with that name. it would then be simple to do whatever you > wanted with the location values stored in the array of each name key. > > a dumb example: > > ######## > > nl_array = [ > ["Hector", "Barcelona"], > ["Bill", "New York"], > ["Ivan", "Moscow"], > ["Hector", "San Francisco"], > ["Bill", "Boston"] > ] > > nl_hash = Hash.new > > nl_array.each{|entry| > unless nl_hash.has_key?(entry[0]) > nl_hash[entry[0]] = [entry[1]] > else > nl_hash[entry[0]] << entry[1] > end > } > > p nl_hash > > ######## > > => {"Ivan"=>["Moscow"], "Bill"=>["New York", "Boston"], > "Hector"=>["Barcelona", "San Francisco"]} > > > hth, > > - j > > -- > Posted via http://www.ruby-forum.com/. > > --90e6ba6e853226f4ac04aea6bfd5--