0

Say I have an array:

s = ["Abc", 123, "Abc", 123, "Abc", 123, "Abc", 123, "Abc", 123]

What would be the best way to turn it into

array = [["Abc",123]["Abc",123]["Abc",123]["Abc",123]["Abc",123]
sawa
  • 165,429
  • 45
  • 277
  • 381
cooltop101
  • 79
  • 7

1 Answers1

2

Use Enumerable#each_slice:

each_slice(n) { ... } → nil
each_slice(n) → an_enumerator
Iterates the given block for each slice of n elements. If no block is given, returns an enumerator.

So you'd say:

s.each_slice(2).to_a

or

s.each_slice(2).entries
mu is too short
  • 426,620
  • 70
  • 833
  • 800