2

I was wondering if it is possible to create dynamic arrays, i.e., arrays with code depending on the user input. If the user enters 3, code creates three arrays. Or if user enters 5, code creates five arrays. Any ideas on how I can do this?

3
  • Do you want these arrays to be created in a double array or separately? Commented Nov 4, 2014 at 16:24
  • Separately so i'm able to reference them individually later on. Commented Nov 4, 2014 at 17:31
  • You can reference a single array within a double array with double_array[0], double_array[1] etc. Commented Nov 4, 2014 at 17:37

2 Answers 2

1
print 'How many arrays? ' #=> suppose 5 is entered
arrays = Array.new(gets.to_i) { [] } #=> [[], [], [], [], [], []]

This will create an array holding 5 different arrays. If you want each to be stored in a separate variable, you can use the fact that Ruby allows you to dynamically create instance variables:

print 'How many arrays? '
number = gets.to_i
number.times.each do |i| # if number is 5, i will be 0,1,2,3,4
  instance_variable_set(:"@array_#{i}", Array.new)
end

p @array_0, @array_1, @array_2, @array_3, @array_4 

Suppose we entered 3 here, the first 3 instance variables (array_0 through array_3) will print [], while the last 2 will print nil (since they lack a value).

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

Comments

1
def create_arrays(n)
  array_collection = []
  n.times {array_collection.push([])}
  array_collection
end

Comments

Your Answer

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