Prev: Bitwise 2010 ( IIT Kharagpur ) An Annual Algorithm Intensive Online Programing Contest
Next: Ruby Threads From C
From: Squawk Boxed on 1 Feb 2010 09:29 I was wondering if it was possible to create a series of arrays through a loop. This doesn't work (I think): for num in 1..10 array_num = Array.new end -- Posted via http://www.ruby-forum.com/.
From: Robert Klemme on 1 Feb 2010 09:43 2010/2/1 Squawk Boxed <vikramjam(a)yahoo.com>: > I was wondering if it was possible to create a series of arrays through > a loop. This doesn't work (I think): > > for num in 1..10 > array_num = Array.new > end Well, it *does* work - only you loose references to a newly created Array immediately. You can try some of these variants: arrs = [] 10.times { arrs << Array.new } arrs = Array.new(10) { Array.new } arrs = (1..10).map { Array.new } Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/
From: Marnen Laibow-Koser on 1 Feb 2010 09:43 Squawk Boxed wrote: > I was wondering if it was possible to create a series of arrays through > a loop. This doesn't work (I think): > > for num in 1..10 > array_num = Array.new > end Of course that doesn't work. You're setting the same variable (array_num) each time. What you should do is use an array of arrays: array_of_arrays = Array.new(10) {Array.new} Best, -- Marnen Laibow-Koser http://www.marnen.org marnen(a)marnen.org -- Posted via http://www.ruby-forum.com/.
From: Aldric Giacomoni on 1 Feb 2010 09:44 Squawk Boxed wrote: > I was wondering if it was possible to create a series of arrays through > a loop. This doesn't work (I think): > > for num in 1..10 > array_num = Array.new > end It works fine, but it will always assign the new array to the same variable. One idea is to create an array, and then add arrays as elements. main_array = Array.new (1..10).times { main_array << Array.new } This may do what you want, but there may also be a more Ruby-ish way, depending on why you need those arrays. -- Posted via http://www.ruby-forum.com/.
From: Robert Klemme on 1 Feb 2010 11:40
2010/2/1 Aldric Giacomoni <aldric(a)trevoke.net>: > Squawk Boxed wrote: >> I was wondering if it was possible to create a series of arrays through >> a loop. This doesn't work (I think): >> >> for num in 1..10 >> array_num = Array.new >> end > > It works fine, but it will always assign the new array to the same > variable. > > One idea is to create an array, and then add arrays as elements. > > main_array = Array.new > (1..10).times { main_array << Array.new } Either use (1..10).each or use 10.times - but (1..10).times won't work: irb(main):002:0> (1..10).times {|*a| p a} NoMethodError: undefined method `times' for 1..10:Range from (irb):2 from /opt/bin/irb19:12:in `<main>' Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/ |