The take()
method is part of the Array
class in Ruby and returns a specified number of elements from an array.
The syntax of the take()
method is as follows:
arrayinstance.take(n) # returns new_array or nil
Note: An
arrayinstance
could be any instance of theArray
class.
The take()
method requires only one argument, which is the number of elements to be taken from the given array instance. The argument needs to be a positive integer, otherwise an error will occur.
The take()
method takes the specified n
number of values from the Array
instance and returns a new Array
instance that contains the values taken from the original Array
. The method will throw an exception if a negative value is passed to it.
The code below shows how the take()
method works in Ruby. Three arrays were created and the take()
method was called on them, with their parameters. Then the values taken by the number specified as parameters are printed to the console.
# declaring arraya = [1, 2, 3, 4, 5]# declaring arrayb = ["a", "b", "c", "d", "e"]# declaring arrayc = ["Ruby on Rails!", "Java", "C++", "Python", "Javascript" ]# take method exampleputs "take() method form : #{a.take(2)}\n\n"puts "take() method form : #{b.take(1)}\n\n"puts "take() method form : #{c.take(3)}\n\n"
When the take()
method is applied to an empty array, nothing is returned.
# create empty arraya = []# prints valueputs "take() method form : #{a.take(3)}" # nothing is formed because array is emtpty
When we pass a negative integer as a parameter to the take()
method, an error is thrown. This is because the take()
method requires a positive integer as a parameter. The error displayed will be:
in take': attempt to take negative size (ArgumentError)
Run the code below to see the error.
# create an arrayanimals = ["cat", "dog", "horse", "mongoose"]# print new formed arrayputs "take() method form : #{animals.take(-3)}" # Error is thrown because parameter is negative