【问题标题】:How do I return an array of arrays with user input?如何返回包含用户输入的数组数组?
【发布时间】:2019-09-26 05:21:53
【问题描述】:

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

我想输入最后一段代码并要求用户输入组号。这应该打印该组中的人,每个人用逗号和空格分隔。组号是“1-indexed”的。这意味着,如果用户输入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 个名称?
  • 不,可以有用户指定的任意数量的组和名称。最后一段代码只需要请求用户希望看到的组号。其他一切都已经在原始代码中实现了。
  • 那么你怎么知道一个组什么时候输入完名字?
  • 我现在有了解决方案,但感谢您的关注。
  • 无论如何请看我的回答,它可能会有所帮助。在将第一个答案标记为“已接受”之前,在 Stackoverflow 上留出时间等待其他可能的答案也是一个好主意,因为有很多方法可以解决相同的问题。

标签: arrays ruby while-loop


【解决方案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

【讨论】:

  • 我需要的是向用户请求输入。例如:输入“输入您的组号”,然后这将返回新的名称组。我知道用“gets”应该很简单......
  • 我更新了我的答案。在我看来,您已经知道如何请求输入并获得它。无论如何,我认为您只需将我的代码粘贴到您的末尾并删除我的第一行
【解决方案2】:

我想这就是你想让你的程序做的事情?尝试运行它:

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}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2021-10-21
    相关资源
    最近更新 更多