Spring 2024 Ruby Exam

Problem 1

Write a main script that accepts two strings as command-line arguments and presents a “diff” of the strings. The strings are each printed on their own line. On the third line, a ^ marks each character that doesn't match and a space silently marks each character that does match. For example:

$ ruby yourscript.rb "happy birthday?" "hippy birfday?"
happy birthday?
hippy birfday?
 ^       ^^^^^^

All three lines terminate in a linefeed character.

Problem 2

Define a function survey that accepts a string composed of votes represented as plus signs, minus signs, and zeroes. It returns a single number representing how the voters lean. For example:

puts survey('----0')
# prints -4

puts survey('+-+')
# prints 1

puts survey('++-+-0+--+0++')
# prints 3

Problem 3

Define class Date that abstracts a particular date. Give it a constructor that accepts three integers for the year, month, and day. Give it getters year, month, and day.

Define also a top-level function named birthday_buddies that accepts a target Date and an array of date strings of the form YYYYMMDD. It returns the dates—in Date rather than string form—that occur on the same month and day as the target date. For example:

target = new Date(1865, 4, 15)
p birthday_buddies(target, %w{20030415 20041009 20010415})
# prints [Date {2003, 4, 15}, Date {2001, 4, 15}]

Don't use loops or each.

Problem 4

Define a function sift that accepts an array of numeric ranges and an array of numbers. It returns an array of arrays in which each inner array contains just the numbers that fall within the corresponding range. The numbers appear in the same order as they do in the original array. For example:

p sift([5..7, 7..20], [7, 0, 5, 15, 4, 6])
# prints [[7, 5, 6], [7, 15]]

Don't use loops or each.

Problem 5

You landed a tech internship in Susville, France. The boss doesn't like the Integer type and has you represent every positive number less than 1000 as a hash whose keys are :ones, :tens, and :hundreds and whose values are the numeric digits at the corresponding place. For example, the number 583 is represented as {ones: 3, tens: 8, hundreds: 5}.

Define function int_to_hash that accepts a Ruby Integer and returns its hash representation. Define also function hash_to_int that accepts a hash representation and returns a Ruby Integer.

Problem 6

Define a class Connector that manages a collection of connections between entities. The entities are identified by their names, which are strings. It has the following methods:

Consider using data structure(s) that expedite this task.