Let's say that we have an array of 6 numbers and
we want to get only the even numbers.
Here is how we can do that.
Ruby provides method filter
which can help us to this in a much simpler way.
First let's see how to use filter
.
Notice that how much shorter the code is with filter
.
Just like map
, filter
also internally builds an array for us and that's why
we don't need to build an array. All we need to do is to tell filter
a condition that it needs to apply on each of the elements.
If an element passes the condition then add that element to the array else reject that element.
Let's see one more example.
We have an array full of strings and
we only want strings which has more than five letters.
We can solve this using filter
like this.
It should be noted that the methods select
and find_all
are identical to filter
in that they all serve to filter elements from an array or hash based on a specified condition.