1

I'm having an array:

arr =["112000666", "10", "111282637", "15", "111342625", "12", "112000674",
      "11", "111488203", "18", "111237150", "20"]

Is there any way to make a 2D array and divided by 2 values? Something like this:

[["112000666", "10"], ["111282637", "15"], ["111342625", "12"],
 ["112000674", "11"], ["111488203", "18"], ["111237150", "20"]]

The number of elements will always be even.

2 Answers 2

4

For rails you can use in_groups_of method:

arr.in_groups_of(2)
  #=> [["112000666", "10"], ["111282637", "15"], ["111342625", "12"],
  #    ["112000674", "11"], ["111488203", "18"], ["111237150", "20"]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! You are my savior!
4

Pure Ruby:

arr.each_slice(2).to_a
  #=> [["112000666", "10"], ["111282637", "15"], ["111342625", "12"],
  #    ["112000674", "11"], ["111488203", "18"], ["111237150", "20"]]

See Enumerable#each_slice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.