How to Use select Method in Ruby: Syntax and Examples
In Ruby,
select is a method used to filter elements from an array or enumerable based on a condition inside a block. It returns a new array containing only the elements for which the block returns true. Use it by calling array.select { |item| condition }.Syntax
The select method is called on an array or enumerable and takes a block with a condition. It returns a new array with elements that meet the condition.
array: The collection you want to filter.select: The method that filters elements.{ |item| condition }: The block where you specify the condition for selecting elements.
ruby
filtered_array = array.select { |item| condition }Example
This example shows how to use select to get all even numbers from an array.
ruby
numbers = [1, 2, 3, 4, 5, 6] even_numbers = numbers.select { |num| num.even? } puts even_numbers.inspect
Output
[2, 4, 6]
Common Pitfalls
One common mistake is forgetting to use a block with select, which will cause an error. Another is expecting select to modify the original array; it returns a new array instead. To change the original array, use select!.
ruby
numbers = [1, 2, 3, 4] # Wrong: missing block # filtered = numbers.select # Correct usage filtered = numbers.select { |n| n > 2 } puts filtered.inspect # Original array is unchanged puts numbers.inspect # To modify original array numbers.select! { |n| n > 2 } puts numbers.inspect
Output
[3, 4]
[1, 2, 3, 4]
[3, 4]
Quick Reference
- Purpose: Filter elements from an array or enumerable.
- Returns: New array with selected elements.
- Block: Condition to select elements.
- Non-destructive: Original array stays the same unless
select!is used.
Key Takeaways
Use
select with a block to filter elements based on a condition.select returns a new array and does not change the original array.To modify the original array, use
select! instead of select.Always provide a block with
select to avoid errors.select works on any enumerable, not just arrays.