From: Xavier Noria Date: 2007-08-03T20:35:02+09:00 Subject: Re: Determining the common prefix for several strings El Aug 3, 2007, a las 6:23 AM, Harry Kakueki escribi�: > If I understood you correctly, I think this will do it. > > r = ["itemz14","item004","item002","item002b","item 5","itemize this"] > > s = [] > a ,b = r.max.split(//), r.min.split(//) > a.each_with_index{|x,y|s << y if x != b[y]} > (0...s[0]).each {|x| print a[x]} Good, so lexicographic order indeed helps. I would prefer to order the array only once though, and construct the prefix right ahead as a string so that the code reads more direct: prefix = '' min, max = items.sort.values_at(0, -1) min.split(//).each_with_index do |c, i| break if c != max[i, 1] prefix << c end puts prefix My approach with splits removed and handling of the corner case where all items are equal is: prefix = items.first (0...items.first.length).each do |i| if items.map {|item| item[i, 1]}.uniq.length != 1 prefix = prefix[0, i] break end end puts prefix That solution does not order the array, but explicitly loops over all the columns in the prefix plus one via map, and uniqs them. The approach based on sort seems a bit better to me. -- fxn