Ruby Method of the Day - Array.last

Posted by Kelly McCauley on Nov 19, 2007

Signature

array.last            #=> object or nil
array.last(number)    #=> new_array

array.last returns the last element of array or it returns nil if array is empty. array.last(number) returns the last number elements of array or it returns an empty array if array is empty.

Examples

1
2
3
4
5
6
7
8
9
10
a = ["a", "b", "c", "d", "e", "f"]

a.last        #=> "f"
[].last       #=> nil

a.last(0)     #=> []
a.last(1)     #=> ["f"]
a.last(4)     #=> ["c", "d", "e", "f"]
a.last(99)    #=> ["a", "b", "c", "d", "e", "f"]
[].last(10)   #=> []

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.last

Trackbacks

Use the following link to trackback from your own site:
http://drotner.org/articles/trackback/73