Spring 2023 Ruby Exam
Problem 1
Write method sum_tween
to accept three parameters: an array of numbers, a lower bound, and an upper bound. It returns the sum of the numbers between the inclusive bounds. For example, sum_tween([1, -5, 8, 9, 20], 8, 10)
→ 17.
Do not use a loop or each
statement.
Problem 2
Write a class UndoValue
that represents a value that changes over time and can be reverted to an earlier state. It has the following public methods:
- A constructor that accepts the initial value as a parameter
-
A getter named
value
for the current value - A setter (with an appropriate name) for the value that assigns a new value but remembers the old value
-
A method
undo
that undoes the value to its most recent prior value. This method can be called an arbitrary number of times. Once the value reaches its initial value, additional calls toundo
have no effect. The value stays the same.
Problem 3
Write a method count_words
that accepts a string of words separated by single spaces. It counts how many times each word appears, and returns the counts in a hash keyed on the words. For example, count_words("i had had enough")
→ {"i" => 1, "had" => 2, "enough" => 1}
.
Do not use a loop or each
statement.
Problem 4
Write method neighbors3
that accepts an array and an index. It returns a comma-separated string of the three values nearest to the index. If values are cut off from the beginning or end, an ellipsis appears in their place. For example:
-
neighbors3([10, 3, 9], 1)
→"10, 3, 9"
-
neighbors3([1, 2, 3, 4], 0)
→"1, 2, 3..."
-
neighbors3([1, 2, 3, 4], 3)
→"...2, 3, 4"
-
neighbors3(%w{H B K Na Cl Pb}, 2)
→"...B, K, Na..."
Assume that the array has at least three elements.
Problem 5
Write a class Person
that has a constructor that accepts a first name and a last name. It has getters first
and last
. It also has a method username
that generates a username, which is the person's last name followed by their first initial, all in lowercase.
Write also a top-level method read_people
that accepts the path to a file as its only parameter. Inside the file is text of this form:
Jacobs,Harriet
Dewey,John
Kosemura,Akira
...
The number of lines in the file is arbitrary. The method reads in the file and returns an array of Person
.
Write also a top-level method read_usernames
that accepts the path to a file of the same format described earlier. It returns an array of the people's usernames.
Problem 6
Write a method wordgrid
that accepts an array of strings, all of the same length. It prints to standard output the letters in the cells of a grid surrounded by lines made of hyphens and pipes. For example, wordgrid(['abc', 'def', 'ghi', 'jkl'])
displays this output:
-------
|a|b|c|
-------
|d|e|f|
-------
|g|h|i|
-------
|j|k|l|
-------