All Pages All Books|
|
||
![]() |
||
|
|
||
|
There are really only three kinds of story elements in our Mad Libs exercise. There’s ordinary prose, questions to ask the user, and reused replacement values.
The last of those is the easiest to identify, so let’s start there. If a value between the ((...)) placeholders has already been set by a question, it is a replacement. That’s easy enough to translate to code:
# A placeholder in the story for a reused value. class Replacement
# Only if we have a replacement for a given token is this class a match. def self.parse?( token, replacements )
if token[0..1] == "((" and replacements.include? token[2..-1] new(token[2..-1], replacements)
else
false end end
def initialize( name, replacements ) @name = name
@replacements = replacements
end
def to_s
@replacements[@name]
end end
Using parse?(), you can turn a replacement value from the story into a code element that can later be used to build the final story. The return value of parse?() is either false, if the token was not a replacement value, or the constructed Replacement object.
Inside parse?(), a token is selected if it begins with a (( and the name is in the Hash of replacements. When that is the case, the name and Hash are stored so the lookup can be made when the time comes. That lookup is the to_s() method.
On to Question objects:
# A question for the user, to be replaced with their answer. class Question
# If we see a ((, it ' s a prompt. Save their answer if a name is given. def self.parse?( prompt, replacements )
if prompt.sub!(/^\(\(/, "")
prompt, name = prompt.split(":").reverse
|
||
|
|
||
|
|
||
All Pages All Books