Ruby

Ruby Find Elements In An Array

In Ruby and other programming languages, arrays allow you to store related information in a list and manage them by a single variable.

Once you have an array, you can manipulate the elements stored in it, such as creating, reading, updating, and deleting elements.

In this short guide, we will explore various ways to find elements in an array.

1. Include Method

To determine if a value is in an array elements’, you can use the include? method.

Values = [10,20,30,40,50]
values.include? 20
=> true

The include? method returns a Boolean value. True if the array contains the specified element and false if the element is not found.

values.include? 100
=> false

2. Using the Select Method

Ruby provides a method called select that allows you to define a specific condition. It then evaluates the elements in the array that match the set condition and returns them in a new array.

values = [10,20,30,40,50]
values.select {|i| i > 33}
=> [40, 50]

The select method is handy for filtering out elements that only match a specific condition.

It is good to note that the select method does not perform the actions in place. However, it creates a new array with matching elements.

To perform the select operation in place of the original array, you can use the select! method.

3. Using the Index Method

To find the index of an element in the array by specifying its value, you can use the index method.

values = [10,20,30,40,50]
values.index 40
=> 3

If the specified value is within the array, the method will return its index, which you can use to fetch the item.

4. Using the Find Method

The find method is similar to the select method. However, it returns only the first value that matches the specified condition. Hence, if the array contains duplicate values, it will only return the first match.

values = [1,2,9,5,4,9,2,1]
values.find {|i| i % 2 == 0}

In the example above, the find method searches the array for the first that matches the specified condition.

In our example, that element is 2. However, four also evaluates to true, but the method does not include it as it’s not the first element.

HINT: Ruby provides a find_all method that works similar to the select method discussed previously.

5. Using the find_index

The find_index method is similar to find. However, it returns the index of the first matching element in the array.

values = [1,2,9,5,4,9,2,1]
values.find_index {|i| i % 2 == 0}
=> 1

The first matching value is at index 1.

Closing

This guide illustrated various methods and techniques you can use to find an element in an array.

Thank you for reading!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list