-1

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.

r15
  • 486
  • 1
  • 8
  • 22

3 Answers3

5
snap1 = snaps.dup
snap2 = snap1.pop(5)
sawa
  • 165,429
  • 45
  • 277
  • 381
2
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]
Santhosh
  • 28,097
  • 9
  • 82
  • 87
  • 2
    You can use `.last(5)` instead. Also note, that if array has repetitions, subtraction will remove all repeated elements. – BroiSatse May 26 '14 at 12:09
  • `snap1 = snaps - snap2` will likely yield wrong results in the case `snaps` contains duplicate entries. – toro2k May 26 '14 at 12:10
2

You can use slice! to create the two arrays:

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

snap2 = snaps.slice!(-5..-1)
# => ["s-n-5", "s-n-3", "s-n-2", "s-n-1", "s-n"] 

snaps
# => ["s-1", "s-2", "s-3", "s-4"]
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93