Skip to content

Instantly share code, notes, and snippets.

@chrisbnt
Created June 21, 2011 02:24
Show Gist options
  • Save chrisbnt/1037109 to your computer and use it in GitHub Desktop.
Save chrisbnt/1037109 to your computer and use it in GitHub Desktop.
Enumerable#longest_common_prefix
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