Ruby | Enumerable first() function
The first() of enumerable is an inbuilt method in Ruby returns the first N elements or the first element of the enumerable. If there is no first element, it returns nil. If there are less than N elements, then it returns all the elements.
Syntax: enu.first(N)
Parameters: The function takes N which signifies the first N elements which is to be returned. If N is not given, then it assumes N = 1.
Return Value: It returns the first or first N elements.
Example 1:
# Ruby program for first method in Enumerable # Initialize enu = (1..10) # Prints enu.first(6) |
Output:
[1, 2, 3, 4, 5, 6]
Example 2:
# Ruby program for first method in Enumerable # Initialize enu = [1, 7, 10, 11] # Prints enu.first |
Output:
1
Example 3:
# Ruby program for first method in Enumerable # Initialize enu = [1, 7, 10, 11] # Prints enu.first(10) |
Output:
[1, 7, 10, 11]
Recommended Posts:
- Ruby | Enumerable none?() function
- Ruby | Enumerable all? function
- Ruby | Enumerable any? function
- Ruby | Enumerable max() function
- Ruby | Enumerable min() function
- Ruby | Enumerable map() function
- Ruby | Enumerable take() function
- Ruby | Enumerable one? function
- Ruby | Enumerable sum() function
- Ruby | Enumerable collect() function
- Ruby | Enumerable sort_by() function
- Ruby | Enumerable sort() function
- Ruby | Enumerable to_a() function
- Ruby | Enumerable group_by() function
- Ruby | Enumerable drop() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


