Ruby Method of the Day - Array.first

Posted by Kelly McCauley on Nov 16, 2007

Signature

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

array.first returns the first element of array or it returns nil if array is empty. array.first(number) returns the first 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.first           #=> "a"
[].first          #=> nil

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

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.first

Trackbacks

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