Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
ruby
communitycreator

What is array.take() in Ruby?

okwudili onyejiaku

Overview

The take() method is part of the Array class in Ruby and returns a specified number of elements from an array.

Syntax

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 the Array class.

Parameters

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.

Return value

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.

Code

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 array
a = [1, 2, 3, 4, 5]
  
# declaring array
b = ["a", "b", "c", "d", "e"]
  
# declaring array
c = ["Ruby on Rails!", "Java", "C++", "Python", "Javascript" ]

# take method example
puts "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"

Example: an empty array

When the take() method is applied to an empty array, nothing is returned.

# create empty array
a = []

# prints value
puts "take() method form : #{a.take(3)}" # nothing is formed because array is emtpty

Example: a negative integer as a parameter

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 array
animals = ["cat", "dog", "horse", "mongoose"]

# print new formed array
puts "take() method form : #{animals.take(-3)}" # Error is thrown because parameter is negative

RELATED TAGS

array
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring