Ruby lab

Part 1: November 17

Problem 1

Write a Ruby method that, given an array, returns another array that consists of all odd-numbered elements of the first array. For instance, given an array [1, 5, 'yes', 'no', 2.7], it returns [1, 'yes', 2.7].

Problem 2

Modify the method in the first problem so that it takes an optional second parameter. If this parameter is an even integer, even-numbered elements should be returned, instead of odd-numbered.

Problem 3

Write a method that takes an array of strings and a block and calls this block on each string. Recall that the keyword to call a block is yield. The syntax for the call is the following:


method(["blah", "Blah"]) {...}
Test the method by passing it a block that prints the result of applying reverse to each string. Print out the original array after the call.
Test it again by passing a block that calls reverse!. Print out the original array. Observe the differences.

Problem 4

Write a method that takes an array and a block and returns a new array where elements are the results of applying the block to each element of the original array and returns the resulting array. Test it on an array of integers and a method that squares each element. Also test it on an array of a different type and a different block. Do not use map for this problem.

Part 2: November 19

Problem 5

Use methods of the class Enumerable to do the following:

  1. Select all strings from a mixed array
  2. Select all non-strings from a mixed array
  3. Select all odd numbers from a range of numbers
  4. Find the shortest string in an array of strings
  5. Concatenate all strings in an array of strings
  6. Flatten an array of arrays (of any type).

Problem 6

Write a class Shape that has coordinates of its enclosing box, i.e. the samllest rectangle that contains it (x, y of the left upper corner, width, and height). Write a Circle and a Rectangle subclasses of this class, with the corresponding initializers. A circle should be created by specifying the coordinates of the center and the radius; a rectangle is its own enclosing box, so specifying x, y, width, height is sufficient.
Write a method that takes an array of shapes and checks if there is a shape that fits into an enclosing box of any other shape. "Fits" means that it is entirely contained within the other enclosing box. For instance, the box with coordinates x = 1, y = 5, width = 4, height = 3 contains the box with x = 3, y = 4, width = 2, height = 2.
Feel free to define any methods and classes that help you accomplish these tasks.


CSci 4651 course.