Ruby - select Function Example

1. Introduction

The select function in Ruby offers a concise and readable way to filter collections based on specified criteria. In this article, we'll explore the select method in detail, covering its primary use cases and showcasing its efficiency in Ruby programming.

The select method is available for arrays and other enumerable objects in Ruby. It iterates over each element of the collection and returns a new collection containing all elements for which the given block returns a true value.

2. Program Steps

1. Define a collection, like an array of numbers or a hash.

2. Apply the select function to filter the collection based on different criteria.

3. Print the filtered results.

3. Code Program

# Step 1: Define an array of numbers and a hash
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
students = {
  Alice: 85,
  Bob: 78,
  Charlie: 93,
  David: 90,
  Eve: 74
}
# Step 2a: Use select to filter even numbers
even_numbers = numbers.select { |num| num.even? }
# Step 2b: Use select to filter students with scores above 80
top_students = students.select { |name, score| score > 80 }
# Step 3: Print the results
puts "Numbers: #{numbers}"
puts "Even Numbers: #{even_numbers}"
puts "Top Students: #{top_students}"

Output:

Numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even Numbers: [2, 4, 6, 8, 10]
Top Students: {:Alice=>85, :Charlie=>93, :David=>90}

Explanation:

1. numbers: This represents the array of integers we will be working with.

2. students: This is a hash with student names as keys and their scores as values.

3. even_numbers: Using the select method, we filter the numbers to return only the even ones.

4. top_students: Here, we employ the select method on a hash. The block receives two parameters (key and value) for hashes. We filter to retain only those students who scored more than 80.

5. The select function simplifies the task of filtering collections based on certain criteria. With its intuitive syntax, it's a go-to method for many Ruby developers when they need to sift through collections.

By leveraging the power of the select method, developers can achieve efficient and readable code when filtering collections in Ruby.


Comments