Ruby take array method

In ruby programming array take() method are use to returns n objects from beginning of array. This method are accept one parameter value which is indicate number of element. Syntax of this method as follows.

Syntax Array.take(n)
Parameter Number of element
Return New resultant array

When array is empty or array contains less than n (parameter value ) element then this method returning new array which contains elements of apply array.

Ruby take() method example

In this section given possible cases to use take() method with proper example. Lets see the few examples to understand its working functionality.

# Example 1

# Test array
record = [1,"code",2,[10,20],3,4,9]

# Test take
a = record.take(2)
b = record.take(4)

# Display array
print(" record ",record)

# Display result
print("\n a : ", a)
print("\n b : ", b)
Ruby take method example 1
 record [1, "code", 2, [10, 20], 3, 4, 9]
 a : [1, "code"]
 b : [1, "code", 2, [10, 20]]

In above example note that take() method return new resulting array when array contains reference (collection and object) then new array share those objects.

In below example, is described the default behavior of this method. Such as when apply this method to empty array. And when parameter value is more than size elements of array.

# Example 2

# Test array
record1 = [11,12,13,14,15]
record2 = []

# Get 2 element
a = record1.take(2)

# More than size of record1
b= record1.take(7)

# Get element from empty array
c = record2.take(4)

# Display array
print(" record1 ",record1)
print("\n record2 ",record2)

# Display result
print("\n a : ", a)
print("\n b : ", b)
print("\n c : ", c)
Ruby take method example 1
 record1 [11, 12, 13, 14, 15]
 record2 []
 a : [11, 12]
 b : [11, 12, 13, 14, 15]
 c : []


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved