Xavier Noria wrote:
> El Aug 3, 2007, a las 2:31 AM, Todd Burch 
>escribi:
> 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

A variant of this is:

list = <<-EOS
item001
item004
item002
item002b
item002C
item 5
item 10
itemize this
EOS
s =  list.split("\n").sort{|a,b|a.length<=>b.length}
pre = 
s.collect{|e|e.split('')[0...(s[0].length)]}.transpose.collect{|e|e.uniq}.reject{|e|e.length>1}.flatten.join('')
p pre # => "item"

Wolfgang N#adasi-Donner
-- 
Posted via http://www.ruby-forum.com/.