From: Logan Capaldo Date: 2007-08-07T10:47:23+09:00 Subject: Re: Determining the common prefix for several strings ------=_Part_75442_7861574.1186451246020 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On 8/6/07, Xavier Noria wrote: > > El Aug 6, 2007, a las 5:13 PM, Stefan Rusterholz escribi=F3: > > > Wow, I'm surprised nobody had the idea of simply using Array#abbrev, > > which is included in the stdlib. > > There's no guarantee you can obtain the maximum common prefix from > its output, because it computes _unambiguous_ prefixes: > > %w{ item1 item2 }.abbrev > =3D> {"item1"=3D>"item1", "item2"=3D>"item2"} > > See, no "item" there, you end up basically with the information you > had before the call. irb(main):027:0> items =3D [ irb(main):028:1* 'item001', irb(main):029:1* 'item004', irb(main):030:1* 'item002', irb(main):031:1* 'item002b', irb(main):032:1* 'item002C', irb(main):033:1* 'item 5', irb(main):034:1* 'item 10', irb(main):035:1* 'itemize this' irb(main):036:1> ] irb(main):039:0> Abbrev.abbrev(items).sort_by { |s,| s.length}.first.first[= 0..- 2] =3D> "item" irb(main):040:0> items =3D ["happy", "happening", "hapless"] =3D> ["happy", "happening", "hapless"] irb(main):041:0> Abbrev.abbrev(items).sort_by { |s,| s.length}.first.first[= 0..- 2] =3D> "hap" irb(main):042:0> items =3D ["c", "b", "a"] =3D> ["c", "b", "a"] irb(main):043:0> Abbrev.abbrev(items).sort_by { |s,| s.length}.first.first[= 0..- 2] =3D> "" irb(main):044:0> I've edited out some false starts. Please feel free to point out any flaws that I've missed Abbrev.abbrev(items).sort_by { |s,| s.length }.first.first[0..-2] > ------=_Part_75442_7861574.1186451246020--