Ruby lab

Due Friday, April 20th at midnight

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

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 3

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.

Problem 4

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).


CSci 4651 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.