简体   繁体   中英

how do i populate a multi dimensional array in ruby

I'm writing a small program that prompts the user to keep listing friends' names one by one (loop until they say stop and break the loop) and then asks the user the number of groups they want to create. the program has to add the first person to group 1, second person to group 2, third person to group 3 etc..in order, for their desired amount of friend groups. then the user can recall each group individual with another prompts after

I'm just wondering how you might go about this, I'm thinking of an empty multidimensional array but i don't know how to add each name to the right places in the array, please can you offer some help.

many thanks

example output

Enter number of groups
3
Enter a name
Mary
Enter a name
Lauren
Enter a name
Awad
Enter a name
Govind
Enter a name
Isla
Enter a name
stop
Enter the number of a group to print out
1
Mary, Govind
Enter the number of a group to print out
2
Lauren, Isla
Enter the number of a group to print out
3
Awad
Enter the number of a group to print out
stop
puts 'Enter number of groups'
no_of_groups = gets.chomp.to_i
groups = Array.new(no_of_groups) { Array.new() }
index = 0

loop do
  puts 'Enter a name'
  name = gets.chomp
  break if name.downcase == 'stop'
  groups[index] << name
  index = (index + 1) % no_of_groups
end

loop do
  puts 'Enter the number of a group to print out'
  group_number = gets.chomp
  break if group_number.downcase == 'stop'
  puts groups[group_number.to_i - 1].join(', ')
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM