jmaxyz jmaxyz - 1 year ago 41
Ruby Question

Is there a Ruby Array method that returns two sub-arrays: one of specified size and another of the remaining contents?

I need to render the contents of the first 5 elements of an array and display "And X more" on a web page. Is there a built-in method on Array (or Enumerable) that easily separates one array into two sub-arrays: the first consisting of up to a fixed size and the second consisting of the array remainder?

I'm looking for one simple method call that will do this for me. Most of the methods that I looked at (like

) use a logical condition to divide the array and don't supply the index to the block.

I just wrote the following code to do what I want. Please save me from myself and direct me to a method that already does it.

class Array
def bifurcate(size=length)
if size < 0
raise ArgumentError, "attempt to bifurcate using negative size"

[take(size), drop(size)]

# => [["a", "b"], ["c", "d", "e", "f", "g"]]
# => [["a", "b", "c", "d", "e", "f", "g"], []]
# => [["a", "b", "c", "d", "e", "f", "g"], []]
# [[], ["a", "b", "c", "d", "e", "f", "g"]]
# ArgumentError: attempt to bifurcate using negative size

Also, let me qualify that I want one simple method call to do what I want. Also consider that the starting array may contain duplicate values and this method needs to respect the original array and return duplicates.

Answer Source
[array.take(3), array.drop(3)]
# [["a", "b", "c"], ["d", "e", "f", "g"]]

Hope it helps :)