How To Filter Array In Ruby

In this blog post, we will explore different ways to filter arrays in Ruby. Filtering arrays is a common operation in programming, and Ruby provides us with several methods to achieve this, including the select, reject, and find_all methods. We will discuss each of them and provide examples to help you understand how to use them effectively.

Using the select method

The select method is used to filter an array based on a given condition. It iterates over each element in the array and returns a new array containing only the elements that satisfy the condition.

Here’s an example:

  numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

  even_numbers = numbers.select { |number| number.even? }

  puts even_numbers.inspect
  # Output: [2, 4, 6, 8]
  

In this example, we used the select method to filter the numbers array and keep only the even numbers.

Using the reject method

The reject method works similarly to the select method but does the opposite. It filters an array by removing elements that satisfy the given condition.

Here’s an example:

  numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

  odd_numbers = numbers.reject { |number| number.even? }

  puts odd_numbers.inspect
  # Output: [1, 3, 5, 7, 9]
  

In this example, we used the reject method to filter the numbers array and remove the even numbers, leaving us with only the odd numbers.

Using the find_all method

The find_all method is an alias for the select method, meaning it works just like the select method and can be used interchangeably.

Here’s an example:

  numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

  even_numbers = numbers.find_all { |number| number.even? }

  puts even_numbers.inspect
  # Output: [2, 4, 6, 8]
  

As you can see, the find_all method behaves just like the select method, and the output is the same.

Conclusion

In this blog post, we learned how to filter arrays in Ruby using the select, reject, and find_all methods. These methods are powerful and easy to use, allowing you to filter arrays based on your specific requirements.