delete_if{}
deletes any element of an array that satisfies a certain condition.
array.delete_if{condition_block}
condition_block
: This is the condition that the target elements need to satisfy to be deleted. For example, this could be a condition for even numbers. So elements that are even will be deleted.
The original array without the deleted elements is returned.
In the example below, we create some arrays and delete some elements using the array.delete{}
function.
# create arrays array1 = [1, 2, 3, 4, 5] array2 = ["a", "b", "c", "d", "e"] array3 = [2015, 2016, 2017, 2018, 2019] # delete elements greater than 2 array1.delete_if{|elem| elem > 2} # delete alphabets less than "d" array2.delete_if{|elem| elem < "d"} # delete dates greater than 2015 array3.delete_if{|elem| elem > 2015} # print modified arrays puts "#{array1}" # [1, 2] puts "#{array2}" # ["d", "e"] puts "#{array3}" # [2015]
In line 7, elements greater than 2 are deleted, so [1, 2]
is printed on the console in line 16.
In line 10, alphabets greater than the character d
are deleted, leaving the array as ["d", "e"]
.
Dates greater than 2015 are deleted on line 13, leaving the array as [2015]
.
RELATED TAGS
CONTRIBUTOR
View all Courses