What is array.delete_if{} in Ruby?
delete_if{} deletes any element of an array that satisfies a certain condition.
Syntax
array.delete_if{condition_block}
Parameter
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.
Return value
The original array without the deleted elements is returned.
Code
In the example below, we create some arrays and delete some elements using the array.delete{} function.
# create arraysarray1 = [1, 2, 3, 4, 5]array2 = ["a", "b", "c", "d", "e"]array3 = [2015, 2016, 2017, 2018, 2019]# delete elements greater than 2array1.delete_if{|elem| elem > 2}# delete alphabets less than "d"array2.delete_if{|elem| elem < "d"}# delete dates greater than 2015array3.delete_if{|elem| elem > 2015}# print modified arraysputs "#{array1}" # [1, 2]puts "#{array2}" # ["d", "e"]puts "#{array3}" # [2015]
Explanation
-
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
dare deleted, leaving the array as["d", "e"]. -
Dates greater than 2015 are deleted on line 13, leaving the array as
[2015].