Homework 4: Due February 21, 2011
Ruby Programming, part 2
1. Ruby Hash
Write a Ruby script which creates a hash containing key-value pairs as shown in the following table:
Animal/Object (Key) | Number of legs (Value) |
Dog | 4 |
Centipede | 100 |
Millipede | 1000 |
Chicken | 2 |
Ant | 6 |
Milking Stool | 3 |
After initializing the hash, the script should display all the known keys (use the keys method to return a list of the keys in a hash).
Then interactively display a prompt and read user input of a type of animal/object. In response, output the number of legs for that animal/object, or an appropriate message if the name is not found. If the name is not found, the user should be prompted to add the animal/object if desired, with an input number of legs and added to the hash. Any changes to the hash should be followed by a display of all keys as was done at the start of the program.
Input should not be case sensitive.
End of input is signaled by the user entering Ctrl-Z.
An example execution of the script could look similar to the following (user input in green):
Milking stool, Centipede, Millipede, Dog, Ant, Chicken
Choose an animal name dog The Dog has 4 legs
Choose an animal name slug Couldn't find Slug, want to add it? y How many legs? 0
Slug, Milking stool, Centipede, Millipede, Dog, Ant, Chicken
Choose an animal name milking stool The Milking stool has 3 legs
Choose an animal name SLUG The Slug has 0 legs
2. Ruby Regular Expressions
The file in words.zip contains more than 38,000 words, one per line. Write a Ruby script which prints the number of words in this file that:
a) contain the string
'sses
'
b) begin with a 'b
' and end with a 'k
'
c) contain a 'b
' interior to the word (not the first
letter) and followed later in the word by a 'k
' interior to the word
(not the last letter)
d) contain a number (string of digits)
e)
do not contain the any of the letters 'm
' through 'z
'
3. Parsing a Java Class
Write a Ruby script that processes a Java file as follows
a) Displays a list of all the identifiers in the file.
Find the rules for properly formed Java identifiers and use this to define a
regular expression. Exclude any reserved words (keywords) from the list since
they are not allowed to be used as identifiers.
b) Display the contents of
the file with all comments removed. Note that Java has three forms of comments.