Skip to content

Instantly share code, notes, and snippets.

@jgarlick
Created September 27, 2013 07:11
Show Gist options
  • Save jgarlick/6725116 to your computer and use it in GitHub Desktop.
Save jgarlick/6725116 to your computer and use it in GitHub Desktop.
def self.process_randoms(text)
stack = []
stored_string = ""
random_choices = []
scanner = StringScanner.new(text)
while match = scanner.scan_until(/[\{\}\|]|\[(one of|or|at random)\]/)
stored_string << match.slice(0, match.length - scanner.matched_size)
case scanner.matched
when "{", "[one of]"
stack.push([random_choices, stored_string])
random_choices = []
stored_string = ""
when "|", "[or]"
if stack.empty?
stored_string << "|"
else
random_choices.push(stored_string)
stored_string = ""
end
when "}", "[at random]"
unless stack.empty?
random_choices.push(stored_string)
selected_choice = random_choices[rand(random_choices.length)]
(random_choices, stored_string) = stack.pop
stored_string << selected_choice
end
end
end
stored_string << scanner.rest if scanner.rest?
stored_string
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment