Home »
Ruby programming
Array.take_while Method with Example in Ruby
Ruby Array.take_while Method: Here, we are going to learn about the Array.take_while method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on February 09, 2020
Array.take_while Method
In this article, we will study about Array.take_while method. You all must be thinking the method must be doing something which is related to taking elements or objects from the Array instance. It is not as simple as it looks. Well, we will figure this out in the rest of our content. We will try to understand it with the help of syntax and demonstrating program codes.
Method description:
This method is a public instance method and defined for the Array class in Ruby's library. This method works in a way that it keeps on passing the objects to the block until the block returns false or nil. When the block returns false or nil, it stops the iteration and returns a new Array instance which contains all previous objects. If you are not providing any block or you are invoking the method without any block, then the method will return an enumerator.
Syntax:
array_instance.take_while -> Enumerator
or
array_instance.take_while{|arr| block}-> new_array or nil
Argument(s) required:
This method does not take any argument. Instead you will have to pass a block.
Example 1:
=begin
Ruby program to demonstrate take_while method
=end
# array declaration
table = [2,4,8,10,12,134,160,180,200]
puts "Array take_while implementation"
puts "Enter the maximum limit:"
num = gets.chomp.to_i
rslt = table.take_while{|i|i<num}
puts "The Array instance returned from the method is:#{rslt}"
Output
Array take_while implementation
Enter the maximum limit:
34
The Array instance returned from the method is:[2, 4, 8, 10, 12]
Explanation:
In the above code, you can observe that we are taking elements from the Array instance with the help of Array.take_while method. We have asked the user for the maximum number and the method is returning true for all the integers which are less than the maximum number. In the end, the Array object which is returned has all the prior elements for which the method has returned true.
Example 2:
=begin
Ruby program to demonstrate take_while method
=end
# array declaration
table = [1,3,4,6,7,8,19,21,22,24,25,99]
puts "Array take_while implementation"
puts table.take_while
Output
Array take_while implementation
#<Enumerator:0x0000561a367d3718>
Explanation:
In the above code, you can observe that the method Array.take_while is returning an enumerator when we are invoking or calling it without any block.