CSC302 2011S Programming Languages

Laboratory: Ruby (3)

Summary:

Prerequisites: The first Ruby lab. The second Ruby lab. Tate, Chapter 2

Contents:

Preparation

a. Create a directory for this lab. I would recommend something like csc302/ruby/lab3, but it's up to you.

b. Start the interactive ruby interpreter with irb.

c. In your browser, you may want to open a link to the code from Tate.

Exercises

Exercise 1: CSV Basics

a. Pick the simplest implementation of the CSV wrapper and verify that it works as advertised.

b. Determine what happens if the rows are shorter than or longer than the number of headers.

Exercise 2: A Constructor

Right now, ActsAsCsv ties the name of the class to the name of the file. Write a constructor that accepts an optional filename.

Exercise 3: Columns

Add a method to the ActsAsCsv class called column that takes one parameter, the name of a column, and returns an array of all the values in that column.

Exercise 4: Columns, Revisited

Using the method_missing hack, support procedures for each of the column names. E.g., if the CSV file has a column named grade, it should be possible to call csv.grade and get that column.

You should use raise "No such method" (or something similar) if an invalid column name is given.

For Those Extra With Extra Time

Extra 1: Rows

Create another class, CsvRow, that represents one row in a CSV file. The class should permit you to extract a value in a row by column number or by name. (Call the methods whatever you'd like.)

Extend your ActsAsCsv class with a method that returns rows by number.

Extra 2: Iteration

Implement an each method for ActsAsCsv that calls its parameter on a each CsvRow.

 

History

Saturday, 22 January 2011 [Samuel A. Rebelsky]

  • Set up placeholder for lab.

Monday, 31 January 2011 [Samuel A. Rebelsky]

 

Disclaimer: I usually create these pages on the fly, which means that I rarely proofread them and they may contain bad grammar and incorrect details. It also means that I tend to update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This document was generated by Siteweaver on Mon Apr 25 08:06:53 2011.
The source to the document was last modified on Mon Jan 31 09:53:56 2011.
This document may be found at http://www.cs.grinnell.edu/~rebelsky/Courses/CSC302/2011S/Labs/ruby-3.html.
A PDF version of this document may be found at http://www.cs.grinnell.edu/~rebelsky/Courses/CSC302/2011S/Labs/ruby-3.pdf

You may wish to validate this document's HTML ; Valid CSS! ; Creative Commons License

Samuel A. Rebelsky, rebelsky@grinnell.edu