Skip to content

Instantly share code, notes, and snippets.

@jamescway
Last active December 14, 2015 10:39
Show Gist options
  • Save jamescway/5073877 to your computer and use it in GitHub Desktop.
Save jamescway/5073877 to your computer and use it in GitHub Desktop.
multi-select-recursive-refactor.rb
def is_token_prefix?(prefix, tokens)
tokens.each { |token| return true if token.start_with?(prefix) }
false
end
def is_token?(str, tokens)
tokens.each { |token| return true if token == str }
false
end
def get_a_token(str, delims)
result = ""
while !is_token_prefix? str[0], delims
result << str[0]
str.slice!(0)
break if str.empty?
end
result
end
def remove_next_delim(str, delims)
temp = ""
while is_token_prefix? str[0], delims
temp << str[0]
str.slice!(0)
break if is_token?(temp, delims)
if is_token?(temp + str[0], delims)
str.slice!(0)
break
end
end
temp
end
def multi_split2(str, delims)
multi(str, delims, [])
end
def multi(str, delims, sum)
return sum if str.empty?
sum << get_a_token(str, delims)
remove_next_delim(str, delims)
multi(str, delims, sum)
end
puts multi_split2("dogxycat", ["og", "y"]).to_s
puts multi_split2('ddxy', ['d']).to_s
puts multi_split2("dogxycat", ["og", "y"]).to_s
puts multi_split2("dogxycat", ["og", "dog"]).to_s
puts multi_split2("dogxycat", ["dog", "do"]).to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment