David Lee
David Lee

Reputation: 601

How do I create a multidimensional array from an array in Ruby?

I need to create a multidimensional array from an array.

For example, let's say the initial array = [1,2,3,4,5,6]

I need a multidimensional array of

[ [1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5],[1,2,3,4,5,6] ]

I feel like this should be so easy, but I am stuck.

Here's what I have so far, which is wrong

def solution(a)
  empty =[]
  a.each do |x|
    new_array = Array(x)
    empty.push(new_array)   
  end
  empty.reverse
end

and I've tried

def solution(a)
  empty =[]
  for i in 1..a.size
    new_array = Array(a.pop)
    empty.push(new_array)   
  end
  empty.reverse
end

Anybody have a solution or suggestion?

EDIT: I realized that I never specified whether the array will consist of more than integers. For my purposes, I am looking for a solution that will accommodate integers or strings.

Upvotes: 0

Views: 105

Answers (4)

Schwern
Schwern

Reputation: 164819

Assuming you want to generate lists of sequential numbers, use 1.upto(6) to iterate 6 times, then make the individual arrays by mapping with 1.upto(i).

1.upto(6).map { |i| 1.upto(i) }

This makes an Enumerator of Enumerators. These should be fine, and you'll save memory if they get large. If you want to force them to be Arrays, add to_a.

1.upto(6).map { |i| 1.upto(i).to_a }

If you want a more generic solution, use Cary's answer.

Upvotes: 2

Cary Swoveland
Cary Swoveland

Reputation: 110675

arr = [1,2,3,4,5,6]

arr.size.times.map { |i| arr[0..i] }
  #=> [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5],
  #    [1, 2, 3, 4, 5, 6]] 

Upvotes: 1

mechnicov
mechnicov

Reputation: 15258

The question is not quite accurate so in more general way:

def multidemensional(ary)
  ary.map { |x| 1.upto(x).to_a }
end
multidemensional([1, 2, 3, 4, 5, 6])
# => [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6]]

multidemensional([2, 2, 3, 7])
# => [[1, 2], [1, 2], [1, 2, 3], [1, 2, 3, 4, 5, 6, 7]]

Upvotes: 0

builder-7000
builder-7000

Reputation: 7627

You could use flatten:

arr = []
arr = [1,2,3,4,5,6].map{ |elm| arr = [arr, elm].flatten }
arr # => [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6]]

Upvotes: 2

Related Questions