Open In App

Ruby | Range first() function

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only.

Syntax: range1.first(X)



Parameters: The function accepts X which is the number of elements from the beginning.

Return Value: It returns an array of first X elements.



Example 1:




# Ruby program for first() 
# method in Range 
  
# Initialize range 
range1 = (0..10)
  
# Prints the first element 
puts range1.first()

Output:

0

Example 2:




# Ruby program for first() 
# method in Range 
  
# Initialize range 
range1 = (0..10)
  
# Prints the first element 
puts range1.first(3)

Output:

0
1
2
Article Tags :