Search code examples
rubyruby-1.9.3

Create a two separate arrays from existing array in ruby


I have a array of n elements say

snaps = ["s-1","s-2","s-3","s-4",..."s-n-2","s-n-1","s-n"] 

now I want to create two diff array such that one array contains last 5 elements and another contains remaining elements.For example

snap1 = ["s-1","s-2","s-3","s-4",...]
snap2 = ["s-n-5","s-n-3","s-n-2","s-n-1","s-n"] 

How can I do this.


Solution

  • snap2 = snaps[-5, 5]
    

    Or

    snap2 = snaps.last(5) # As suggested my BroiSatse
    

    will give you an array with the last 5 elements

    For the remaining, you can do

    snap1 = snaps[0..-6]