DEV Community

Prathamesh Sonpatki
Prathamesh Sonpatki

Posted on

Array manipulation tricks in Ruby

Let's say we have an array and we do not want the first element of the array. Ruby provides a method Array#drop which removes the elements from the array and returns the result.

>> args = [1,2,3,4]
=> [1, 2, 3, 4]
>> args.drop(1)
=> [2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Good thing about this method is that it does not manipulate the original array.

>> args = [1,2,3,4]
=> [1, 2, 3, 4]
>> args.drop(1)
=> [2, 3, 4]
>> args
=> [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

If we don't want first two elements of the array, we can pass two as the argument to drop.

>> args = [1,2,3,4]
=> [1, 2, 3, 4]
>> args.drop(2)
=> [3, 4]
Enter fullscreen mode Exit fullscreen mode

Ruby also has a method Array#drop_while which drops elements up to, but not including the first element for which the predicate returns false or nil.

>> args
=> [1, 2, 3, 4]
>> args.drop_while { |a| a < 3 }
=> [3, 4]
>>
Enter fullscreen mode Exit fullscreen mode

This method is useful when you know for certain that you don't want certain elements from the start of the array.

Ruby also has Array#take and Array#take_while which return the elements from the start based on the argument.

>> args
=> [1, 2, 3, 4]
>> args.take_while { |a| a < 3 }
=> [1, 2]
>> args.take(2)
=> [1, 2]
Enter fullscreen mode Exit fullscreen mode

Follow me on Twitter to know more tips and tricks about Ruby πŸ˜„

Top comments (0)