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]
2
  • Your expected output is not valid Ruby expression. Commented Apr 24, 2018 at 6:05
  • 2
    ...and it's not just the missing commas. As an aside, "s", as in "string", is not the best name for an array. "a", "arr" or "array" would be more fitting. Commented Apr 24, 2018 at 6:29

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.