CSC 270
Homework 4
Assigned Oct 11, due Oct 20

This assignment is to be done in Ruby. There are lots of implementations available for download from, and as far as I know they should work more or less interchangeably. There are, however, different versions of Ruby, most notably 1.9.2 and 1.8.7. Most of what we do in this class should work equally well in both, but just to make sure, tell me (in a comment near the top of your homework) which version you're using.

You are encouraged to do this in teams of two, both students working together on each function; if you do this, turn in one homework with both names on it.

For all functions, follow the design recipe: each function must have a contract, a good collection of test cases, and a function definition.

For testing, you might want to use this testing framework, written by Chris Dollard. Read the source code to learn how to use it.

In order to get your homeworks graded quickly, I won't actually grade every one of these problems, but rather a sample including problems of various levels of difficulty. The rest are practice. If there's one that you want to make sure I look at, call my attention to it when you turn in the homework.

Within each heading, the problems are arranged more or less in increasing order of difficulty. If one of them really stumps you, try going on to a different heading, and then come back to this problem.

    Defining functions

  1. Choose five of problems 1-13 in homework 1, and re-write them in Ruby.

  2. Define functions factorial and fibonacci, using the obvious recursion.

  3. Using classes and methods

  4. Define a function reverse_sort that takes in an Array of numbers and returns them, sorted in decreasing order. (Hint: You can write the body of the function in one fairly short line by using built-in methods of the Array class.)

  5. Defining classes and methods

  6. Define a Posn class with two numeric fields x and y, with the obvious constructor and getters.

    Add a to_s method to the Posn class, returning a nicely-formatted string representation of the Posn. (This is equivalent to toString in Java.)

    Re-do problems 14-18 from homework 1 in Ruby, replacing the functions with methods of the Posn class and renaming them according to Ruby naming conventions. Instead of add-posns, write a method named +.

Last modified:  Tue Oct 11 07:46:57 EDT 2011
Stephen Bloch /