DEV Community

Prathamesh Sonpatki
Prathamesh Sonpatki

Posted on

14 3

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 😄

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay