3.1 Basic Array Operations
Transforming arrays
Now on to more interesting things, but with a little tip from me first. Try running this:
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]
.
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.
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.
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:
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:
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.
Congratulations, guest!
Sign in to save your progress
or