From: Michael Glaesemann Date: 2007-08-03T10:31:00+09:00 Subject: Re: Determining the common prefix for several strings On Aug 2, 2007, at 19:31 , Todd Burch wrote: > 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. I don't know of a particularly elegant way to do this in Ruby, but my initial thoughts are list = <<-EOS item001 item004 item002 item002b item002C item 5 item 10 itemize this EOS # sort by length: prefix can't be longer than shortest string. items = list.split("\n").sort_by { |i| i.length } # use shortest as prefix first = items.shift items.inject(first) do |prefix, item| next prefix if item.match(/^#{prefix}/) # have to go char by char n = 0 for i in 0..(prefix.length - 1) do break if prefix[i] != item[i] n = i end prefix[0..n] end Michael Glaesemann grzm seespotcode net