-
-
Save kapowaz/6725795 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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