Ruby last array method

In the Ruby programming language the last() array method is returning single or last n elements from the array. It is an inbuilt method that takes a parameter. When parameter values are not provided, it returns the last element of the array when the array is not empty. The syntax as follows.

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

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

The parameter of this method is optional, when parameters are provided it indicates the elements of the array that are to be taken from the last of the array.

Ruby last() method example

This method are not modifies actual array, And result of this method returns single and multiple element when array contain elements. lets see few examples to understand functionality of this method.

# Our array
arr1 = [3,6,2,8]
arr2 = [true,false,[1,4,3]]
# Get last element
a1 = arr1.last
a2 = arr2.last()

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

# Print return value
print("\n a1 : ",a1)
print("\n a2 : ",a2)
Ruby last method example A
 Array arr1 : [3, 6, 2, 8]
 Array arr2 : [true, false, [1, 4, 3]]
 a1 : 8
 a2 : [1, 4, 3]

Note that the array is not empty and it returns a single value when applying the last() method. When the last element of array is not literal, when they reference the object. Which is shown in the example above.

The second example, Using parameter values to derive more than one element of an array that exists in the last.

# Example 2

# Our array
arr1 = [3,6,2,8]
arr2 = [true,false,[1,4,3]]
# Getlast 2 elements
a1 = arr1.last(2)
a2 = arr2.last(2)

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

# Print return value
print("\n a1 : ",a1)
print("\n a2 : ",a2)
Ruby last method example B
 Array arr1 : [3, 6, 2, 8]
 Array arr2 : [true, false, [1, 4, 3]]
 a1 : [2, 8]
 a2 : [false, [1, 4, 3]]

Note that last(n) are returning a new array which contains last n elements of array.



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