Tuesday, 15 February 2011

ruby - Create arrays via code -



ruby - Create arrays via code -

i wondering if possible create dynamic arrays, i.e., arrays code depending on user input. if user enters 3, code creates 3 arrays. or if user enters 5, code creates 5 arrays. ideas on how can this?

print 'how many arrays? ' #=> suppose 5 entered arrays = array.new(gets.to_i) { [] } #=> [[], [], [], [], [], []]

this create array holding 5 different arrays. if want each stored in separate variable, can utilize fact ruby allows dynamically create instance variables:

print 'how many arrays? ' number = gets.to_i number.times.each |i| # if number 5, 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 entered 3 here, first 3 instance variables (array_0 through array_3) print [], while lastly 2 print nil (since lack value).

ruby

No comments:

Post a Comment