>From: Xavier Noria <fxn / hashref.com>
>Reply-To: ruby-talk / ruby-lang.org
>To: ruby-talk / ruby-lang.org (ruby-talk ML)
>Subject: Re: Determining the common prefix for several strings
>Date: Fri, 3 Aug 2007 12:22:45 +0900
>
>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
>
>

Here is yet another way to solve this problem.

min_len = items.min{ |i,j| i.length <=> j.length }.length
common_prefix = ""
(0...min_len).each do |i|
  col = items.inject(""){ |sum,elem| sum << elem[i] }.squeeze
  if col.length > 1
    puts common_prefix
    break
  end
  common_prefix << col
end

Ron

_________________________________________________________________
Find a local pizza place, movie theater, and morethen map the best route! 
http://maps.live.com/default.aspx?v=2&ss=yp.bars~yp.pizza~yp.movie%20theater&cp=42.358996~-71.056691&style=r&lvl=13&tilt=-90&dir=0&alt=-1000&scene=950607&encType=1&FORM=MGAC01