0
0
Rubyprogramming~5 mins

Select/filter for filtering in Ruby

Choose your learning style9 modes available
Introduction
Select or filter helps you pick only the items you want from a list, like choosing your favorite fruits from a basket.
When you want to find all even numbers from a list of numbers.
When you need to get all names that start with a certain letter from a list of names.
When you want to keep only the items that meet a certain condition, like all fruits that are red.
When you want to filter out unwanted data from a collection, like removing all expired products from a list.
Syntax
Ruby
array.select { |item| condition }
# or
array.filter { |item| condition }
Both select and filter do the same thing in Ruby.
The block inside { } tells Ruby which items to keep.
Examples
Keeps only even numbers from the list.
Ruby
[1, 2, 3, 4, 5].select { |n| n.even? }
Keeps fruits that start with the letter 'a'.
Ruby
['apple', 'banana', 'avocado'].filter { |fruit| fruit.start_with?('a') }
Keeps numbers greater than 15.
Ruby
[10, 15, 20, 25].select { |num| num > 15 }
Sample Program
This program picks only the even numbers from the list and prints them.
Ruby
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = numbers.select { |n| n.even? }
puts "Even numbers: #{even_numbers.join(', ')}"
OutputSuccess
Important Notes
The original array does not change; select returns a new array.
You can use any condition inside the block to filter items.
If no items match, select returns an empty array.
Summary
Select/filter helps you pick items from a list based on a condition.
Use select or filter with a block that returns true for items you want to keep.
The result is a new list with only the chosen items.