0
0
RubyHow-ToBeginner · 3 min read

How to Use take and drop Methods in Ruby Arrays

In Ruby, take(n) returns the first n elements of an array, while drop(n) skips the first n elements and returns the rest. Both methods do not modify the original array but return new arrays.
📐

Syntax

The take and drop methods are called on arrays with a single integer argument n.

  • array.take(n): Returns a new array with the first n elements.
  • array.drop(n): Returns a new array skipping the first n elements.

Both methods return arrays and do not change the original array.

ruby
array.take(n)
array.drop(n)
💻

Example

This example shows how take returns the first few elements and drop skips them, returning the rest.

ruby
numbers = [10, 20, 30, 40, 50]

first_two = numbers.take(2)
rest_after_two = numbers.drop(2)

puts "Original array: #{numbers}"
puts "Take 2: #{first_two}"
puts "Drop 2: #{rest_after_two}"
Output
Original array: [10, 20, 30, 40, 50] Take 2: [10, 20] Drop 2: [30, 40, 50]
⚠️

Common Pitfalls

One common mistake is expecting take or drop to modify the original array. They return new arrays instead.

Also, passing a number larger than the array size to take returns the whole array, while drop returns an empty array.

ruby
arr = [1, 2, 3]

# Wrong: expecting original array to change
arr.take(2)
puts arr.inspect  # Still [1, 2, 3]

# Correct: assign result to a variable
new_arr = arr.take(2)
puts new_arr.inspect  # [1, 2]
Output
[1, 2, 3] [1, 2]
📊

Quick Reference

MethodDescriptionExampleResult
take(n)Returns first n elements[1, 2, 3, 4].take(2)[1, 2]
drop(n)Skips first n elements[1, 2, 3, 4].drop(2)[3, 4]

Key Takeaways

Use take(n) to get the first n elements of an array without changing it.
Use drop(n) to skip the first n elements and get the rest as a new array.
Both methods return new arrays and do not modify the original array.
Passing n larger than array size returns the whole array for take, and empty array for drop.
Always assign the result of take or drop to a variable if you want to use the changed array.