Skip to main content

Ruby first array method

In Ruby programming the first() array methods can return a single or several elements at the beginning of an array. By default, this method returns the first element. This method takes one parameter value which is indicate number of element at beginning. Many elements can be obtained using parameter values. This syntax is as follows.

# Get first element
v = arr.first
# or 
v = arr.first()

# To get one and more than one element
v = arr.first(n) # n indicates number of element
# v contains the returning value

When array is empty and get first element in array then this method are returns a nil value.

Ruby first() method example

Here given few examples to use this method. Which is describe its working functionality. Let take an example to get single element.

# Our array
arr = ["ok",3,6,10]

# Get first element
v1 = arr.first
v2 = arr.first()

# Display array element
print(" Array ",arr)

# Print return value
print("\n v1 : ",v1)
print("\n v2 : ",v2)
Ruby first method example A
 Array ["ok", 3, 6, 10]
 v1 : ok
 v2 : ok

This is returning a first element when parameters are not given. The second example, to return multiple elements using a parameter value.

# Our array
arr = [10,20,30,40,[1,4,8],50,60,70,80,90]

# Get first 5 element
v1 = arr.first(5)
# Get first 3 element
v2 = arr.first(3)

# Display array element
print(" Array ",arr)

# Print return value
print("\n v1 : ",v1)
print("\n v2 : ",v2)
Ruby first method example B
 Array [10, 20, 30, 40, [1, 4, 8], 50, 60, 70, 80, 90]
 v1 : [10, 20, 30, 40, [1, 4, 8]]
 v2 : [10, 20, 30]

Important point, first(n) is returning a new array which contains initial an element. When element is form of collection of objects then they point to reference

Ruby first() method default behavior

Two main point of first method, First when array empty then first() it returns a nil (None) value. And first(n) method return empty array. And the second first (in) method returns the full array if the parameter value exceeds the size of the array.

# Test arrays
arr1 = []
arr2 = [1,2,4]

# Get first element
a1 = arr1.first()

# Get first 5 element
a2 = arr2.first(5)

# Get element in empty array
a3 = arr1.first(3)

# Display array element
print(" Array arr1 ",arr1)
print("\n Array arr2 ",arr2)

# Print return value
print("\n a1 : ",a1)
print("\n a2 : ",a2)
print("\n a3 : ",a3)
Ruby first method example C
 Array arr1 []
 Array arr2 [1, 2, 4]
 a1 : 
 a2 : [1, 2, 4]
 a3 : []


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