Skip to content

Instantly share code, notes, and snippets.

@cuzzo
Last active July 7, 2018 18:17
Show Gist options
  • Save cuzzo/2acd28e58436213505eb2bf676a95bc2 to your computer and use it in GitHub Desktop.
Save cuzzo/2acd28e58436213505eb2bf676a95bc2 to your computer and use it in GitHub Desktop.
def parse(str)
matches = str.scan(/\([^|]+\|[^)]+\)/)
pairs = matches.map { |match| match[1...-1].split("|") }
(pairs.count - 1)
.times
.to_a
.reduce(pairs[0]) { |acc, i| acc.product(pairs[i + 1]) }
.map { |substition_array| substition_array.flatten }
.map do |subs|
matches
.zip(subs)
.reduce(str) do |acc, (match, sub)|
acc.gsub(match, sub)
end
end
end
input = "(I|you) (want|need) to (buy|purchase) (this|that)?"
puts parse(input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment