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"]
Tweet