To filter elements of an array based on a condition in Ruby, you can use methods like select or reject along with blocks.
In this example,
numbers
containing integers.select
method with a block to filter out even numbers into a new array named even_numbers
.numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = numbers.select { |num| num.even? }
puts "Even Numbers: #{even_numbers}"
Even Numbers: [2, 4, 6, 8, 10]
In this example,
words
containing strings.select
method with a block to filter strings by their length into a new array named filtered_words
.words = ["apple", "banana", "cherry", "date", "fig"]
filtered_words = words.select { |word| word.length > 5 }
puts "Filtered Words: #{filtered_words}"
Filtered Words: ["banana", "cherry"]
In this tutorial, we learned How to Filter Elements of an Array based on a Condition in Ruby language with well detailed examples.