Fall 2022 Ruby Exam

Problem 1

Write a function crank that gets a line of input from the user and then displays it uppercase and cranked 45 degrees clockwise. For example, if the user enters sock, this is the output:

S
 O
  C
   K

Each character is succeeded by a linebreak.

Problem 2

Write a class Datums whose constructor accepts an array of numbers. Its method mean gives the average number. Its method median gives the number that would appear in the middle of the list if it were sorted. If the list has no single middle element, it gives back the number halfway between the two middle elements. Its method numbers gives back the array in the exact same form that it was given to the constructor.

Assume the array contains at least one number.

Problem 3

Suppose you've got one hash that maps names to jobs. Then you've got another hash that maps jobs to salaries. You want a hash that maps names to salaries. Write a function jump_hash that accepts two hashes and returns a hash that maps the keys of the first to the values of the second. For example, jump_hash({'Trina' => 'astronaut'}, {'astronaut' => 200000}){'Trina' => 200000}.

Problem 4

Write a class Book with a constructor that accepts a title and author. Give it getters.

Also, say you've got an array of arrays in which each inner array has two elements: a book title and an author name. You want an array of Book objects. Write a top-level method embooks that receives the array and returns an array of Book instances. Use higher-order functions; do not use each or a for loop.

Problem 5

Suppose you are given an array of people. Each person is represented as a hash with keys :first and :last. Write a function five_lasts that receives such an array and returns an array of the last names of the people whose first names are five characters or fewer.

Use higher-order functions; do not use each or a for loop.

Problem 6

Write a function trade that reads from the first line of input a list of numbers separated by spaces. On the second line is a number \(n\) of trades that are to occur. On the remaining \(n\) lines are pairs of indices. The function swaps the elements indicated by each pair and returns the array after all swaps have been applied. For example, suppose you have this input:

4 9 7 -6
2
0 1
1 3

The array [9, -6, 7, 4] is returned.