0

I'm trying to create some arrays in some threads and name them after a fixnum between 1 and 30 like the following:

times = 30 n=0 thread = [] while n < times thread << Thread.new(n) {|x| array#{x} = Array.new() ... } end 

How can I do that?

2
  • This is definitely a time to consider what you are doing and why. Variable names are for humans. The computer doesn't care (and will munge the name you give it). Store this information in a collection(Array, Hash...). An array even has the benefit of number based index's, which seems to be what you want to do. Commented Dec 29, 2012 at 23:02
  • thanks for suggestion. I don't mean to do that in purpose but didn't realize there's a way as you and gmalette addressed. Commented Dec 30, 2012 at 3:49

2 Answers 2

2

Ruby does not allow you to create variable names from strings in the same way that PHP does. In a case such as this you could use an array or a hash instead.

times = 30 n=0 arrays = [] thread = [] while n < times thread << Thread.new(n) {|x| arrays[x] = Array.new() ... } end 

You can also use more rubyish constructs instead of while, such as Fixnum#times.

arrays = [] threads = 30.times.map do |n| Thread.new do arrays[x] = Array.new # ... end end > arrays #=> [[], [], [], ....] > threads #=> [#<Thread:0x007fe3f22a2320 dead>, #<Thread:0x007fe3f22a2208 dead>, ...] 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for giving out the code. And yes, I should work on how to think in ruby way :)
0

If you don't mind using instance variables rather than local variables, you can do what you are trying to do (whether it is a good idea to design code in this way is another question).

1.upto(times) do |i| instance_variable_set("@array#{i}".to_sym, []) end 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.