1

I have been scouring the internet for an answer and can't seem to make it work. I'm pretty new using Ruby so please be patient. I am trying to write a program that asks user to choose how many arrays they want to create and that automatically create and name these arrays.

Here's what I have so far, please assume that the user will just input an integer. So if the user types 3 it will create myArray1, myArray2, myArray3

puts 'how many arrays do you want to create?'
number_of_arrays = gets.chomp.to_i

(1..number_of_arrays).each do |i|
  myArray+"#{i}" = Array.new 
end

I am aware that myArray+"#{i}" = Array.new doesn't work but I am trying to find a way to do that, any suggestions and help is welcomed. Thank you!

  • 3
    Make an array of arrays. It may be possible to dynamically create local variables using reflection, but it's definitely not what you *want* to do. For instance, how would you know which variables are "safe" to refer to if you don't know which variables exist? – Silvio Mayolo Oct 17 '22 at 20:09
  • Follow @Silvio's advice. Since v1.8 it has not been possible to create local variables dynamically. – Cary Swoveland Oct 17 '22 at 21:37
  • Does this answer your question? [Dynamically set local variables in Ruby](https://stackoverflow.com/a/28767601/895789) – Alter Lagos Oct 17 '22 at 21:39
  • 1
    I agree with all previous commenters - this is a terrible idea. My suggestion is to put the arrays in a Hash, something like `arrays = {"array1" => [1,2,3], "array2" => [4,5,6] }`. Easy to construct, iterate, pinpoint the one you want, contained etc. – steenslag Oct 17 '22 at 23:16

1 Answers1

0

You can't create variables dynamically in ruby. But you can use an hash.

puts 'how many arrays do you want to create?'
number_of_arrays = gets.chomp.to_i
array_of_arrays = {}

number_of_arrays.times do |i|
  array_of_arrays["array#{i+1}".to_sym] = []
end

That will return an hash that will look like that:

{:array1=>[], :array2=>[], :array3=>[], :array4=>[], :array5=>[]}
FoxBall
  • 55
  • 5