3.1 Basic Array Operations
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#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.
is the standard Ruby idiom for filtering elements.
In the following code, try extracting the strings that are longer than five characters.
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
Okay! Hands-on time. Delete all the even numbers from the array given below.
Sign in to save your progress