Gurmukh Singh Gurmukh Singh - 1 month ago 10
Ruby Question

Adding an Array to an Array Ruby

Im trying to learn how to add arrays into arrays, I have the following code:

puts "would you like to save a data set"
response = gets.chomp

if response == "y"
puts "create a new dataset?"
create_data_set = gets.chomp
while create_data_set == "y"
puts "what do you want to name the data set?"
dataset = gets.chomp
dataset = Array.new
puts 'would you like to add some grades to the array?'
store_grades_response = gets.chomp
while store_grades_response == "y"
puts 'enter grade ->'
grade = gets.chomp.to_i
dataset << grade
puts 'would you like to store another grade?'
store_grades_response = gets.chomp
end
all_data_sets = Array.new
all_data_sets.push(dataset)
puts "would you like to create a new data set?"
create_data_set = gets.chomp
end
end

puts all_data_sets


Im basically asking a user to enter a array name which should create an array, add values to the array and if required by the user add some more arrays and values to it. At last the array should be added to an array. And then I'm trying to display all the arrays.

The code works fine, I'm looping through everything but when it
puts all_data_sets
It only shows the last array that was created? i would like to store all the arrays within the one array called
all_data_sets

Answer

The problem is that you are creating a new array all_data_sets at the end of each loop. One solution will be to have it before the loop.

puts "would you like to save a data set"
response = gets.chomp
all_data_sets = []
if response == "y"
  puts "create a new dataset?"
  create_data_set = gets.chomp
  while create_data_set == "y"
    puts "what do you want to name the data set?"
    dataset = gets.chomp
    dataset = Array.new
    puts 'would you like to add some grades to the array?'
    store_grades_response = gets.chomp
    while store_grades_response == "y"
        puts 'enter grade ->'
        grade = gets.chomp.to_i
        dataset << grade
        puts 'would you like to store another grade?'
        store_grades_response = gets.chomp
    end
    all_data_sets << dataset
    puts "would you like to create a new data set?"
    create_data_set = gets.chomp
  end
 end

puts all_data_sets

This way, you keep pushing the datasets into the all_data_sets after each loop.

I hope this is explanatory enough.

Comments