CS 214 Lab 4: Ruby


Begin by using your favorite text editor to edit the file log_table.rb. Take a moment to study it, to see how it implements our basic algorithm, and compare it to the other "programs" you've seen.

Today we'll be looking at repetition. Ruby provides a for loop for solving counting problems, along with a while and until loop. The until loop works like a while loop, except that it runs until the condition is true (syntactical sugar really). Let's look at a BNF for these three loop types:

LoopStatement ::= LoopClause StatementList end
LoopClause    ::= for identifier in Range | while Expression | until Expression
Range         ::= Integer..Integer | Integer...Integer

These kinds of loops work as you would expect in other languages. The for loop iterates over a range of values. There are two distinct types of ranges in ruby, a two dot range and a three dot range. The two dot form is inclusive, while the three dot form is exclusive. For example: 0..4 will count from 0 to 4, while 0...4 will count from 0 to 3.

Since this is a counting problem, the for loop would seem like the natural choice. However, if we take that route we'll run into a problem: Ruby's for loop will only increment by 1, and we need to be able to increment by arbitrary step-values.

Our solution then is to use a while loop. Our while should run so long as our start variable is less than or equal to our stop variable.

In order to actually compute the logarithms, we'll use Ruby's log10() function. The log10() is a member of the Math class, so you'll have to invoke it by sending a message to Math, using Math.log10().

We can use Ruby's puts statement to print a row of our table. But puts will only display a single string. We could write out each piece of the row with separate puts (or puts) statments, or we could use the Ruby string concatenation operator >> to build up an output string and then display that string.

But a better approach is to use Ruby's string inlining mechanism: By surrounding a numeric Value with #{ Value } within a string literal, Ruby will replace this reference with the Value, effectively inserting the numeric value into the string.

Using string inlining, write a single statement to print out a row.

Then, all that's left to do is to increment our counting variable by the increment variable the user provided.

Be sure to test your program on a variety of input values.

When you are certain it is correct, use script to list your program and show that it executes correctly.

That concludes the Ruby part of this lab.


Calvin > CS > 214 > Labs > 04 > Ruby


This page maintained by Joel Adams.