Skip to content

Instantly share code, notes, and snippets.

@imouaddine
Created November 6, 2014 19:49
Show Gist options
  • Save imouaddine/8284d641984307280363 to your computer and use it in GitHub Desktop.
Save imouaddine/8284d641984307280363 to your computer and use it in GitHub Desktop.
Minimum distance between two words in a string
def distance(a,b)
words = "I am a good girl".split(/\W+/)
a_found = false
b_found = false
prev = nil
words.each_with_index do |word, index|
if word == a
prev ||= index
a_found = true
end
if word == b
prev ||= index
b_found = true
end
if a_found && b_found
return index - prev
end
end
-1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment