Created
June 21, 2011 02:24
-
-
Save chrisbnt/1037109 to your computer and use it in GitHub Desktop.
Enumerable#longest_common_prefix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Enumerable | |
def longest_common_prefix | |
common = first | |
self[1..-1].each do |item| | |
length_to_test = [item.length, common.length].min | |
while length_to_test > 0 | |
if item[0..(length_to_test-1)] === common[0..(length_to_test-1)] | |
common = common[0..(length_to_test-1)] | |
break | |
end | |
length_to_test -= 1 | |
return nil if length_to_test == 0 | |
end | |
end | |
common | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment