Home »
Ruby programming
Array.drop_while Method with Example in Ruby
Ruby Array.drop_while Method: In this tutorial, we are going to learn about the Array.drop_while method with syntax, examples.
Submitted by Hrithik Chandra Prasad, on December 25, 2019
Ruby Array.drop_while Method
In the last articles, we have studied about Array.select and Array.reject methods which give output to the user based on certain conditions. The method Array.drop_while is also a non-destructive method.
Method description:
Array.drop_while method works similarly to a loop. As the method, itself contains the word "while" which makes us think that this method is related to a while loop. The operation is just the opposite of while loop. While, while loop works as it processes the things until the condition is not falsified, Array.drop_while method discards or drops the elements until it does not find the element which is specified inside the block. It will print every element if it does not find the element in the Array instance which is defined inside the block of the method. If the specified element lies between two elements of the Array instance, then it will start printing from the greatest one. This method does not through an exception in such a case. It simply drops the elements until it does not find the defined element.
Syntax:
Array.drop_while{|var| #condition}
Parameter(s): This method does not accept any parameter instead a Boolean condition is required inside the block.
Example 1:
=begin
Ruby program to demonstrate Array.drop_while
=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 element after which you want to see the result"
lm = gets.chomp.to_i
flag = false
num.each {|nm|
if nm == lm
flag = true
end
}
if flag == true
puts "Elements after #{lm} are:"
puts num.drop_while { |a| a < lm }
else
puts "Element not found"
end
Output
Enter the element after which you want to see the result
5
Elements after 5 are:
5
6
7
8
9
10
23
11
33
55
66
12
Explanation:
In the above code, you can see that this method requires a sequenced Array of elements. It has printed all the elements which are lying after the element 10. Here, first, we have checked the presence of the element in the Array with the help of Array.each then we have carried out the further processing.
Example 2:
=begin
Ruby program to demonstrate Array.drop_while
=end
# array declaration
num = [1,2,3,4,5,6,7,8,9,10,23,11,33,55,66,12]
print num.drop_while{|a|}
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 23, 11, 33, 55, 66, 12]
Explanation:
In the above code, you can observe that when you are not specifying any condition inside the method then it is printing every element of the Array object.