Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
take_while
ruby
communitycreator

What is array.take_while in Ruby?

okwudili onyejiaku

Overview

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.

Syntax

array.take_while{|obj|block}

Parameters

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.

Return value

The value returned is an array.

Code example

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}"

Explanation

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

array
take_while
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring