CSc600 – Homework: Ruby Dr. Jozo Dujmović
The goal of this homework is to practice programming in Ruby and prepare for the final exam. For each problem, your homework must contain the source program followed by the results of its execution.
1. Write a single Ruby demo program that illustrates the use of all main Ruby iterators (loop, while, until, for, upto, downto, times, each, map, step, collect, select, reject). The program should have a few lines illustrating loop, followed by a few lines illustrating while, and so on).
2. Write Ruby recognizer methods limited? and sorted? that expand the Ruby class Array. The expression array.limited?(amin,amax) should return true if amin ≤ a[i] ≤ amax for all values of i. The expression array.sorted? should return the following:
0
+1
-1
if the array is not sorted
if a[0] ≤ a[1] ≤ a[2] ≤ … (increasing sequence) if a[0] ≥ a[1] ≥ a[2] ≥ … (decreasing sequence)
Show examples of the use of this method.
3. Create a Ruby class triangle with initalizer, accessors, and member functions for computing the perimeter and the area of arbitrary triangles. Make also a member function test that checks sides a, b, and c and classifies the triangle as (1) equilateral, (2) isosceles, (3) scalene, (4) right, and (5) not a triangle. Right triangle can be either isosceles or scalene. Compute the perimeter and area only for valid triangles (verified by test). Show examples of the use of this class.
4. Create a Ruby class Sphere. Each sphere is characterized by the instance variable radius. For this class create the initializer and the following methods:
area – a method that returns the area of the sphere (a 4r2)
volume – a method that returns the volume of the sphere (v 4r3 / 3)
Create the class Ball that inherits properties from the class Sphere and adds a new instance variable color. Then create the class MyBall that inherits properties from the class Ball and adds a new instance variable owner. Write the method show that displays the instance variables of the class MyBall. Show sample applications of the class MyBall.