-1

I want to create variable names like like a1, a2..

 n.times { |n|
  puts "enter number of rows and columns for #{n} array"
  rows = gets.to_i
  cols = gets.to_i
  a+"#{n}" = Array.new(rows,'w') {Array.new(cols,'w')}
 }

Error:

syntax error, unexpected '=', expecting '}' "a#{n}" = Array.new(rows,'w') {Array.new(cols,'w')}

1 Answers1

2

While it's generally possible to create dynamically named local variables in Ruby, this is usually not necessary and is usually a sign of bad software design.

Instead, you should use normal data strictures to hold your data. In your case, you can use a Hash, e.g.

arrays = {}
n.times do |n|
  puts "enter number of rows and columns for #{n} array"
  rows = gets.to_i
  cols = gets.to_i
  arrays["a#{n}"] = Array.new(rows,'w') {Array.new(cols,'w')}
end

You can then access the defined arrays as arrays["a1"] or a specific cell in your nested arrays as arrays["a1"][1][3].

Holger Just
  • 52,918
  • 14
  • 115
  • 123
  • so arrays is a hash now, I need it as an array, how can I do that? – Soubridge Monish Jul 10 '18 at 18:36
  • If it can be an array, just declare it as one up front and set the new arrays based on the index of |n| in your iterator. I read your original post to mean "how do I give arbitrary dynamic names to a group of things", but if the names aren't arbitrary and what you really want is a[0], a[1], a[2], then it's a much simpler question (and doesn't need the hash in the middle) – Marc Talbot Jul 10 '18 at 18:39
  • puts 'enter number of 2d arrays' arrays = [] n = gets.chomp.to_i n.times { |n| puts "enter number of rows and columns for #{n} array" rows = gets.to_i cols = gets.to_i arrays.push Array.new(rows,"#{n}"){Array.new(cols,"#{n}")} } . thanks, this worked – Soubridge Monish Jul 10 '18 at 18:44
  • if `arrays` should just be an array of the elements you could also use `arrays = n.times.map { ...; Array.new(rows,'w') {Array.new(cols,'w')} }` (also this is throwing a lot of warnings, might want to just change it to `Array.new(rows) {Array.new(cols,'w')` – Simple Lime Jul 10 '18 at 18:51
  • Since Ruby v1.8.7 it has not been possible to create local variables dynamically. In v1.8.7 and earlier versions that could be done using `eval`. – Cary Swoveland Jul 10 '18 at 19:25
  • Since this code represents an array of arrays, it's probably better to use a straight array (`arrays[1]`) instead of some kind of hash (`arrays['a1']`) which confuses what's going on. – tadman Jul 10 '18 at 19:56