Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
quick naive is_substring implementation
def is_substring?(s1, s2)
match = false
if s2.length > s1.length
s1_chars, s2_chars = s1.split(''), s2.split('')
possible_matches = []
s2_chars.each_with_index do |c, i|
possible_matches << [c, i] if c == s1_chars.first
possible_matches = {|c,i| s2_chars.slice(i,s1.length).join}
match = possible_matches.any? {|candidate| candidate == s1 }
elsif s2 == s1
match = true
return match
is_substring?("teapot", "I'm a little teapot short and stout.") or raise "FAILED"
is_substring?("foo", "foobar") or raise "FAILED"
is_substring?("bar", "foobar") or raise "FAILED"
is_substring?("FizzBuzz", "FizzBuzz") or raise "FAILED"
!is_substring?("BuzzFizz", "FizzBuzz") or raise "FAILED"
!is_substring?("baz", "foobar") or raise "FAILED"
!is_substring?("baz", "zfoobarba") or raise "FAILED"
puts "PASSED"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment