On Aug 3, 10:31 am, Todd Burch <pro... / burchwoodusa.com> wrote:
>
> 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 this has been done to death, but here's my preferred code:

  list = %{
    item001
    item004
    item002
    item002b
    item002C
    item 5
    item 10
    itemize this
  }.strip.map { |line| line.strip }.sort_by { |str| str.length }

  prefix = list.first.dup

  until prefix.empty? or list.all? { |str| str =~ /^#{prefix}/ }
    prefix.chop!
  end

  p prefix


I didn't think of using chop! until someone else posted a solution
with that in it.  It's the first really good use of chop! I've seen.

This solution also demonstrates the lovely #emtpy? and #all? methods.
(I know #all? has been seen before in this thread, but it's such a
handy method.)

Cheers,
Gavin