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].
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.
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.
reverse!
. Print out the original array. Observe the
differences.
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.
Use methods of the class Enumerable to do the following:
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.