Skip to content

Instantly share code, notes, and snippets.

@johncarney
Created November 13, 2016 10:13
Show Gist options
  • Select an option

  • Save johncarney/ef355be7eac16b96ca0f09bafad5e389 to your computer and use it in GitHub Desktop.

Select an option

Save johncarney/ef355be7eac16b96ca0f09bafad5e389 to your computer and use it in GitHub Desktop.
Find the longest common prefix of a bunch of arrays, or a bunch of strings
def common_array_prefix(*arrays)
arrays.reduce do |a, b|
index = a.zip(b).index { |x, y| x != y }
a[0...index]
end
end
def common_string_prefix(*strings)
common_array_prefix(*strings.map(&:chars)).join("")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment