如何使用用户输入返回数组数组?

时间:2019-05-08 12:57:00

标签: arrays ruby while-loop

下面的代码会将姓名分成几组(例如,第一人称进入第一组,第二人称进入第二组,等等)。

我想输入最后一段代码,并要求用户输入组号。然后,应打印该组中的人员,每个人员之间用逗号和空格隔开。组号为“ 1索引”。这意味着,如果用户输入1,则应该打印第一组,而不是第二组。继续向用户询问(最终)组号,直到用户输入stop

puts "How many groups would you like?"
group_num = gets.chomp.to_i

array = Array.new(group_num) { [] }

puts "Enter one name at a time"
count = 0
 while input_name = gets.chomp
  if input_name == "stop"
    break
  else puts "Give me a name"
   array[count] << input_name
   count += 1
   count = 0 if count == group_num
  end
 end

array.inspect

因此,如果array = [["John", "Steve"], ["Judy", Pete"]]并且请求的组号为2,则输出应打印:"Judy, Pete"(在同一行上)。

2 个答案:

答案 0 :(得分:1)

给出数组,所需的索引非常简单

array = [["John", "Steve"], ["Judy", "Pete"]]
puts "tell me which group you want with a number"
number = gets.to_i
if (1..array.length).include?(number)
  puts "people: #{array[number - 1].join(", ")}"
else
  puts "Number element not present"
end

答案 1 :(得分:0)

我想这就是您想要程序执行的操作?尝试运行它:

array = []
puts "How many groups would you like?"
group_num = gets.chomp.to_i

group_num.times do
  puts "\nEnter one name at a time"
  a = []
  loop do
    puts "Give me a name or 'stop' to stop adding names"
    input_name = gets.chomp
    break if input_name == "stop"
    a << input_name
  end
  array << a
end

array.each_with_index{|a, i| puts "#{i+1}. #{a}" }
puts "select number which group you want"
group = gets.chomp.to_i - 1
puts "you selected group: #{array[group].to_s}"