From: Xavier Noria Date: 2007-08-03T11:26:38+09:00 Subject: Re: Determining the common prefix for several strings El Aug 3, 2007, a las 2:31 AM, Todd Burch escribi�: > I have several strings to analyze. The strings are the names of a > list > of things that were once ordered and now are not. A typical array of > names might look like this: > > item001 > item004 > item002 > item002b > item002C > item 5 > item 10 > itemize this > > I want to parse these names and determine that "item" is the common > prefix. > > I know how to armstrong my way through it a character at a time, > but I'm > thinking that Ruby probably has a very elegant way of doing this that > I'm not familiar with yet. This is a solution that avoids going char by char: items = [ 'item001', 'item004', 'item002', 'item002b', 'item002C', 'item 5', 'item 10', 'itemize this' ] min_length = items.map {|i| i.length}.min cuts = items.map {|i| i.split(//)[0, min_length]} cuts.transpose.each_with_index do |t, i| if t.uniq.length != 1 puts cuts.first[0, i].join('') break end end We first check which is the length of the shortest string in the array, then split by chars to store those many ones, and then transpose the matrix. Note that transposing is OK because we cut the strings. That's longer to explain than to write it in Ruby as you see. Once you get the transpose you can go row by row to detect the one that has more than one distinct element. Again that's easy delegating the job to uniq. -- fxn