使用数组、循环和哈希 - 不知道如何 finish/expand 这段代码

Using arrays, loops, and hashes- don't know how to finish/expand this code

我正在 Ruby 中编写一个程序来练习数组等,但我不确定下一步该做什么。我真的不知道如何把所有东西放在一起。建议会有所帮助。谢谢

我和任意数量的朋友一起卖衬衫($2)和鞋子($6)。我想创建一个接受以下输入的程序。

它会输出:

这是我目前的情况:

https://gist.github.com/greenbottle88/e17ec8406aade496e38a9140d39c3052

这就是我所知道的全部,我不确定从这里到哪里去。现在我收到 "undefined local variable or method `seller' for main:Object" 的错误。但除了那个错误,我只是不知道下一步该怎么做,我确定我尝试过的东西需要一些修复。

它说错误在第 40 行。这应该让您知道在哪里可以找到该错误。如果我们转到第 40 行,我们会看到您调用

seller << sellers_array

但是,我们当前的 scope 中没有定义卖家。 seller 是在循环内而不是在循环外定义的,因此在循环结束后,我们无法访问该 seller 变量。要解决此问题,只需全局定义卖家(在循环之前),然后您就可以访问该变量。

您的代码中还有其他问题 - 但 Whosebug 并不是人们真正解决代码中所有问题或为您做功课的地方。我希望我的解释可以帮助您解决最初的错误。对于您在项目中遇到的下一个错误:

  • 查看错误指向的行号
  • Google 错误
  • 尝试解决错误
  • 仅当您已经用尽所有其他在线资源但仍然卡住时,才在 Whosebug 上创建一个新问题。

我还建议阅读 Ruby 中有关 debugging 的内容。调试是一项在学校中没有得到应有的强调的技能,但它是一项您应该尝试掌握的非常有价值的技能。

我认为这可能是您链接的代码的工作版本。看里面的评论。 然后你必须在数组上工作以获得你想要的信息。

puts "Welcome to your Sale Tracker! Answer some questions below to learn more about your business. Press ENTER to get started."

# Wait for user to press ENTER
pause = STDIN.gets

# Creating arrays
sellers_array = []
shirt_profit_array = []
shoe_profit_array = []
total_profit_array = []
net_profit_array = []

# Using a loop to keep prompting the user for information until they have input all their sellers

loop do

  puts "Name of seller:"
  seller = gets.chomp!

  puts "How many shirts did #{seller} sell?"
  shirts_sold = gets.chomp!.to_i # you must convert the string input to integer

  puts "How many of #{seller}'s shirts remained unsold?"
  shirts_unsold = gets.chomp!.to_i # you must convert the string input to integer

  puts "How many shoes did #{seller} sell?"
  shoes_sold = gets.chomp!.to_i # you must convert the string input to integer

  puts "How many of #{seller}'s  shoes remained unsold?"
  shoes_unsold = gets.chomp!.to_i # you must convert the string input to integer

  puts "Do you have another seller you would like to add? If yes, press ENTER. If no, type 'n'"

  sellers_array << seller

  shirt_profit = shirts_sold * 2 # assignment works this way, == is a comparison
  shirt_profit_array << shirt_profit

  shoe_profit = shoes_sold * 6 # assignment works this way, == is a comparison
  shoe_profit_array << shoe_profit

  total_profit = shirt_profit + shoe_profit # assignment works this way, == is a comparison
  total_profit_array << total_profit

  net_profit = (shirt_profit - (shirts_unsold * 2)) + (shoe_profit - (shoes_unsold * 6)) # assignment works this way, == is a comparison
  net_profit_array << net_profit

  command = STDIN.gets
  break if command.chomp! == "n"

end # you must do calculation and fill arrays inside the loop and each time the loop runs

puts "shirt_profit_array " + shirt_profit_array.to_s
puts "shoe_profit_array" + shoe_profit_array.to_s
puts "total_profit_array" + total_profit_array.to_s
puts "net_profit_array" + net_profit_array.to_s