The take_while
element will take elements of an array and loop them in a block until the condition specified in the block returns false
or nil
. It then returns an array of elements iterated and matched the condition.
If no block is specified with the take_while
method, then an Enumerator
is returned.
array.take_while{|obj|block}
obj
: This represents each element in the array that is passed to the block.
block
: This is the part where the elements are iterated, provided that the block condition remains true
.
The value returned is an array.
The example below shows the use of the take_while
method.
# create array arr1 = [1, 2, 3, 4, 5] arr2 = [10, 12, 13, 14, 20] # use take_while a = arr1.take_while {|elem| elem < 3} b = arr2.take_while {|elem| elem % 2 == 0} # print out returned values puts "#{a}" puts "#{b}"
From the code above, [1,2]
is returned from arr1
because they are less than 3. The iteration stopped when the condition became false
, i.e., when 3 was encountered.
The same is to be said of arr2
. The loop continues for elements 10
and 12
and stops at 13
because the condition remained true
for them but became false
for 13
.
RELATED TAGS
CONTRIBUTOR
View all Courses