From: Brian Candler Date: 2008-09-22T22:37:05+09:00 Subject: Re: Merging two arrays Chris Chris wrote: > I would like to merge these two arrays. The article number is to be the > identifier. > > Thus, I would like an array like this as the result: > ["Amazon",121212,"Harry Potter","www.amazon.com/abc"] Are these two arrays already aligned and of the same size? If so just iterate using each_with_index, or look at Array#zip If they are not aligned, or there are items in one list which are not in the other, then you need to be clearer about your requirements. - What do you want to happen if an item is in 'products' but not in 'links', or vice versa? - What do you want to happen if there are multiple items in the 'links' list which match an item in the 'products' list, or vice versa? One possibility: * iterate across products. * a product with no link gives a nil in the link column. * a link with no product is ignored. * if there are multiple links matching a product, only the first is used. In that case you could just write: products.each do |product| link = links.find { |link| link[0] == product[1] } product[3] = link ? link[1] : nil end If your links list is huge, it may be worth building a hash of article_number=>url first, rather than doing a linear search of the links array each time round. But you may wish to consider a couple of other things first: * make a class for Product and Link. Then you can say product.ref instead of product[1], link.url instead of link[1] etc. The code will be much easier to read. * consider whether your article numbers are guaranteed unique across all suppliers. That is, is there any chance that Amazon have a book 121212 and Waterstones have a different book that they also call 121212? If so, maybe you want to change your links structure to links << ["amazon",121212,"www.amazon.com/abc"] In database-speak, ("amazon",121212) is a composite key. If the article reference is an ISBN then that may be irrelevant. But ISBNs need to be strings I believe, due to use of the "X" character. -- Posted via http://www.ruby-forum.com/.