last() is a Array class method which returns the last element of the array or the last ‘n’ elements from the array. The first form returns nil, If the array is empty .
Syntax: Array.last()
Parameter: Array
n – no. of elements
Return: last element of the array or the last ‘n’ elements from the array
Example #1 :
a = [ 18 , 22 , 33 , nil , 5 , 6 ]
b = [ 1 , 4 , 1 , 1 , 88 , 9 ]
c = [ 18 , 22 , nil , nil , 50 , 6 ]
puts "last : #{a.last(5)}\n\n"
puts "last : #{b.last(4)}\n\n"
puts "last : #{c.last()}\n\n"
|
Output :
last : [22, 33, nil, 5, 6]
last : [1, 1, 88, 9]
last : 6
Example #2:
a = [ "abc" , "nil" , "dog" ]
b = [ "cow" , nil , "dog" ]
c = [ "cat" , nil , nil ]
puts "last : #{a.last(5)}\n\n"
puts "last : #{b.last(4)}\n\n"
puts "last : #{c.last()}\n\n"
|
Output :
last : ["abc", "nil", "dog"]
last : ["cow", nil, "dog"]
last :