Today I Learned

hashrocket A Hashrocket project

Grab first N elements from an array

Have you ever wanted to grab the first n elements from an array?

You might think to do something like this:

fruit = ["apple", "banana", "blueberry", "cherry", "dragonfruit"]

# Grab the first 3 elements of the array
fruit[0...3]
=> ["apple", "banana", "blueberry"]

Well you could just use Array#take and tell it how many elements you want to take:

fruit = ["apple", "banana", "blueberry", "cherry", "dragonfruit"]

# Grab the first 3 elements of the array
fruit.take(3)
=> ["apple", "banana", "blueberry"]

Bonus: There is also Array#take_while which takes a block and passes elements until the block returns nil or false

fruit.take_while {|f| f.length < 8 }
=> ["apple", "banana"]
fruit.take_while {|f| f.length < 10 }
=> ["apple", "banana", "blueberry", "cherry"]
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.