Skip to content

Instantly share code, notes, and snippets.

@jamescway
Created February 27, 2013 16:15
Show Gist options
  • Save jamescway/5049133 to your computer and use it in GitHub Desktop.
Save jamescway/5049133 to your computer and use it in GitHub Desktop.
require 'ruby-debug'
def multi_split(str, tokens)
results = []
buffer = ""
maybe_token = false
temp_str = ""
str.each_char do |c|
if maybe_token
if is_token?(temp_str + c, tokens)
maybe_token, temp_str = reset_state(maybe_token, temp_str)
results << buffer
buffer = ""
elsif is_token_prefix?(temp_str + c, tokens)
temp_str << c
else
maybe_token, temp_str = reset_state(maybe_token, temp_str)
end
else
if(is_token_prefix?(c, tokens))
maybe_token = true
temp_str << c
if is_token?(temp_str, tokens)
maybe_token, temp_str = reset_state(maybe_token, temp_str)
results << buffer
buffer = ""
end
else
buffer << c
end
end
end
results << buffer
results
end
def reset_state(maybe_token, temp_str)
temp_str=""
maybe_token = false
return maybe_token, temp_str
end
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
puts multi_split("dogxycat", ["og", "y"]).to_s
puts multi_split('ddxy', ['d']).to_s
#puts multi_split('ddxy', ['d']) == ['', '', 'xy']
#puts multi_split('dogxycat', ['og', 'y']) == ['d', 'x', 'cat']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment