3.1 Basic Array Operations

Transforming arrays

Now on to more interesting things, but with a little tip from me first. Try running this:

Example Code:

Output Window

You'll notice that the output, [2, 3, 4, 5, 6] is the result of applying the code inside the curly brace to every single element in the array. The result is an entirely new array containing the results. In Ruby, the method map is used to transform the contents of an array according to a specified set of rules defined inside the code block. Go on, you try it. Multiply every element in the array below by 3 to get [3, 6 .. 15].

Output Window

Ruby aliases the method Array#map to Array#collect; they can be used interchangeably. The Class#method syntax is the standard way of referring to Ruby methods and you will see it a lot in this book.

Filtering elements of an Array

Filtering elements in a collection according to a boolean expression is a very common operation in day-to-day programming. Ruby provides the rather handy select method to make this easy.

Example Code:

Output Window

The method select is the standard Ruby idiom for filtering elements. In the following code, try extracting the strings that are longer than five characters.

Output Window

Deleting elements

One of the reasons Ruby is so popular with developers is the intuitiveness of the API. Most of the time you can guess the method name which will perform the task you have in your mind. Try guessing the method you need to use to delete the element '5' from the array given below:

Hint

Say, "array delete 5"

Output Window

I guess that was easy. What if you want to delete all the elements less than 4 from the given array. The example below does just that:

Example Code:

Output Window

You'll notice that Ruby methods with multiple words are separated by underscores (_). This convention is called "snake_casing" because a_longer_method_looks_kind_of_like_a_snake.

Okay! Hands-on time. Delete all the even numbers from the array given below.

Hint

If the number (n) is even then n%2 == 0

Output Window

Doing this in languages like C or Java would take you a lot of boiler plate code. The beauty of Ruby is in its concise but readable code.

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2024 by Sidu Ponnappa and Jasim A Basheer