Home »
Ruby Tutorial
Ruby Array.keep_if Method
By IncludeHelp Last updated : November 28, 2024
In the last articles, we have studied the Array methods namely Array.select, Array.reject and Array.drop_while, all these methods are non–destructive methods which means that they do not impose any changes in the actual values of elements residing in the Array instance. If you want to make the above methods destructive, you can add an “!” after the method name. For instance, Array.select! is the destructive version of Array.select. We have also learned about Array.delete_if the method which is already destructive by nature.
In this article, we will learn about the Array method Array.keep_if which is also destructive by nature like the delete_if method.
Description and Usage
This method is used to select elements from the instance of the Array class at the same instant. This method is just opposite of Array.delete_if method because Array.delete_if method deletes the elements from the Array which do not satisfy the condition provided inside the block on the other hand Array.keep_if method keeps or saves the elements which satisfy the condition specified inside the block of the method. This method will remove all the elements from the Array instance if you do not specify or provide any condition inside the block.
Syntax
Array.keep_if{|var|#condition}
Parameters
This method does not accept any arguments instead it requires a Boolean condition for operation.
Example 1
=begin
Ruby program to demonstrate Array.keep_if
=end
# array declaration
num = [1,2,3,4,5,6,7,8,9,10,23,11,33,55,66,12]
# user input
puts "Enter the your choice (a)keep even numbers (b) keep odd numbers"
lm = gets.chomp
if lm == 'a'
puts "Even numbers are:"
print num.keep_if { |a| a % 2 ==0 }
elsif lm == 'b'
puts "Odd numbers are:"
print num.keep_if { |a| a % 2 !=0 }
else
puts "Invalid Input"
end
Output
RUN 1:
Enter the your choice (a)keep even numbers (b) keep odd numbers
a
Even numbers are:
[2, 4, 6, 8, 10, 66, 12]
RUN 2:
Enter the your choice (a)keep even numbers (b) keep odd numbers
b
Odd numbers are:
[1, 3, 5, 7, 9, 23, 11, 33, 55]
Explanation
In the above code, you can observe that the method is keeping all the elements that are satisfying the condition provided inside the block of Array.keep_if method. If the user is asking to keep odd numbers, then output is shown in RUN 2 and when the user is asking for even numbers, the output is shown in RUN 1.
Example 2
=begin
Ruby program to demonstrate Array.keep_if
=end
# array declaration
num = [1,2,3,4,5,6,7,8,9,10,23,11,33,55,66,12]
print num.keep_if{|a|}
puts ""
print num
Output
[]
[]
Explanation
In the above code, you can observe that if you are not specifying any condition inside the method block, then it is deleting or removing all the elements from the Array instance.