0

I am trying to learn Ruby, and arrays are giving me some trouble. I have input that I flatten down to the pattern "name, number, name, number". I then want to make an array of 2-element arrays, each containing a name and the next number.

When I push these 2-element arrays into another array the seem to automatically flatten to a 0-dimensional array. What I want is the final array to be of size [N/2][2], N being number of names, or numbers in the input.

http://pastie.org/3542269

The puts with the comment does not happen until all of the elements from the pairs array has been printed, so it looks like this:

Name
1
Name
2
Name
3

When I expected this:

Name
1

Name
2

Name
3

I guess my questions are:

  • How do I put arrays inside an array, to make a jagged one?
  • How do I keep track of how many dimensions my arrays are in Ruby? It's so much easier when you have to declare a size.

1 Answer 1

4
some_array = [[["Name 1", "value 1"], ["Name 2", "value 2"]], [["Name 3", "value 3"], ["Name 4", "value 4"]]]

array = some_array.flatten
new_array = array.each_slice(2).map do |a, b|
  [a,b]
end
#=> [["Name 1", "value 1"],
#=> ["Name 2", "value 2"],
#=> ["Name 3", "value 3"],
#=> ["Name 4", "value 4"]]

which is similar to some_array.flatten(1)

Sign up to request clarification or add additional context in comments.

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.