jmaxyz jmaxyz - 4 months ago 15
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

Enumerable#partition
) 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"
end

[take(size), drop(size)]
end
end


('a'..'g').to_a.bifurcate(2)
# => [["a", "b"], ["c", "d", "e", "f", "g"]]
('a'..'g').to_a.bifurcate(20)
# => [["a", "b", "c", "d", "e", "f", "g"], []]
('a'..'g').to_a.bifurcate()
# => [["a", "b", "c", "d", "e", "f", "g"], []]
('a'..'g').to_a.bifurcate(0)
# [[], ["a", "b", "c", "d", "e", "f", "g"]]
('a'..'g').to_a.bifurcate(-1)
# 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
[array.take(3), array.drop(3)]
# [["a", "b", "c"], ["d", "e", "f", "g"]]

Hope it helps :)