All Pages All Books|
|
||
![]() |
||
|
|
||
|
pairs as they are needed. It prints a question, sub()ing a key name out if needed. You can see that the answer is read from the user and shoved right into the Hash under the $1 key. Exactly what’s in that $1 variable is the trick. Notice that the original gsub() from the lower puts() call sets $1 to the entire Mad Libs question. However, the Hash block sometimes performs another substitution, which overwrites $1. If the substitution was named, $1 would be set to that name. Otherwise, the sub( ) call will fail, and $1 will be unaltered. Then, because we’re talking about a Hash here, future access to the same key will just return the set value, bypassing the tricky block.
Again, the above previous has a few bad habits, but it also uses some rare and interesting Ruby idioms to do a lot of work in very little code.
Additional Exercises
1. Extend the Mad Libs syntax to support case changes.
2. Enhance your solution to support the new syntax.
|
||
|
|
||
|
|
||
All Pages All Books