From: Brian Candler Date: 2007-08-07T18:15:26+09:00 Subject: Re: Determining the common prefix for several strings > until prefix.empty? or list.all? { |str| str =~ /^#{prefix}/ } > prefix.chop! > end The trouble with that is that it won't work properly if #{prefix} contains regexp special characters, and it may even bomb out: irb(main):001:0> prefix = "abc[" => "abc[" irb(main):002:0> "abc[def" =~ /^#{prefix}/ RegexpError: invalid regular expression; '[' can't be the last character ie. can't start range at the end of pattern: /^abc[/ from (irb):2 irb(main):003:0> You can use Regexp::escape to fix that, but then you're still building a regexp every time round the loop. That's why I think String#index is better here.