user1538594
user1538594

Reputation:

Create arrays via code

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?

Upvotes: 2

Views: 46

Answers (2)

Darkmouse
Darkmouse

Reputation: 1939

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

Upvotes: 1

daremkd
daremkd

Reputation: 8424

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).

Upvotes: 1

Related Questions