DEV Community

Mbonu Blessing
Mbonu Blessing

Posted on • Edited on

Beginners guide to using array select method

Hello everyone,

This week, we will looking into an array method called select and how to use it.

The select method is one of the class method of the Array class that returns a new array of values that is true for the block that is passed to it.

Given an example array of numbers;

example_array1 = [1, 2, 3, 4, 5, 6]

To select all even numbers;

 example_array1.select { |item| item.even? }

# -> [2, 4, 6]

To select all odd numbers;

 example_array1.select { |item| item.odd? }

# -> [1, 3, 5]

Given another example array of strings

example_array2 = ['dog', 'chicken', 'cow', 'goat']

To select all string whose count is greater than or equal to 4;

 example_array2.select { |item| item.length >= 4 }

# -> ["chicken", "goat"]

To select all string whose count is equal to 3;

 example_array2.select { |item| item.length = 3 }

# -> ["dog", "cow"]

Given another example array of strings and numbers

example_array3 = ['dog', 4, 'chicken', 8,  'cow', 10,  'goat']

To select all the strings in the array;

 example_array3.select { |item| item.class == String }

# -> ["dog", "chicken", "cow", "goat"]

To select all the numbers in the array;

 example_array3.select { |item| item.class == Integer }

# -> [4, 8, 10]

Please feel free to add other ways you have used the select method.

Until next week.

Top comments (0)