From: Xavier Noria Date: 2007-08-03T12:22:45+09:00 Subject: Re: Determining the common prefix for several strings El Aug 3, 2007, a las 4:46 AM, Xavier Noria escribi�: > splits = items.map {|i| i.split(//)} > (0...splits.length).each do |i| > if splits.map {|s| s[i]}.uniq.length != 1 > puts items.first[0, i] > break > end > end There's a bug in the upper limit of the range, it should be the length of some element of the splits splits = items.map {|i| i.split(//)} (0...splits.first.length).each do |i| if splits.map {|s| s[i]}.uniq.length != 1 puts items.first[0, i] break end end We could compute the length of the shortest string and use that finer upper limit, but that's not necessary because even in the case that the shortest string is the common prefix, we would get some nil in the map through columns in the next iteration, and thus at least two distinct values. On the other hand there's the corner case when all strings are equal, that's not handled in the above code because they way to do it depends on the details. Please forgive those many revisions, I guess I need some sleep at 5:22 AM. -- fxn