DEV Community

Mbonu Blessing
Mbonu Blessing

Posted on • Edited on

4 1

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]
Enter fullscreen mode Exit fullscreen mode

To select all even numbers;

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

# -> [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

To select all odd numbers;

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

# -> [1, 3, 5]
Enter fullscreen mode Exit fullscreen mode

Given another example array of strings

example_array2 = ['dog', 'chicken', 'cow', 'goat']
Enter fullscreen mode Exit fullscreen mode

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

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

# -> ["chicken", "goat"]
Enter fullscreen mode Exit fullscreen mode

To select all string whose count is equal to 3;

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

# -> ["dog", "cow"]
Enter fullscreen mode Exit fullscreen mode

Given another example array of strings and numbers

example_array3 = ['dog', 4, 'chicken', 8,  'cow', 10,  'goat']
Enter fullscreen mode Exit fullscreen mode

To select all the strings in the array;

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

# -> ["dog", "chicken", "cow", "goat"]
Enter fullscreen mode Exit fullscreen mode

To select all the numbers in the array;

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

# -> [4, 8, 10]
Enter fullscreen mode Exit fullscreen mode

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

Until next week.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay