0

This works:

#Loop naming accounts====================

num = 0 #<--Generic counting variable

loop do

    print ("\nEnter account name or press 'q': > ")

    names[num] = gets.chomp

        if names[num] == "q"
            break   
        end

    puts ("The account name is #{names[num]}.")

    num += 1

end

The obvious problem here is that I don't want "q" to be one of the accounts.

This doesn't work:

#Loop naming accounts====================

num = 0 #<--Generic counting variable

loop do

    print ("\nWould you like to add an account? [1 - yes] [2 - no]: > ")

    varr = nil

    varr = gets.chomp.to_i

    if varr == 2
        break
    end

    names[num] = gets.chomp

    puts ("The account name is #{names[num]}.")

    num += 1

end

This sends my terminal to a completely black screen. Questions:

  1. Why does the first example work for breaking out of the loop, but the second one will not?

  2. Why is the second example weirdly breaking to a completely blank screen rather than throwing an error, etc?

  3. How do I properly do this?

Thanks!

4

1 回答 1

0
  1. 如果您使用 2 退出,则第二个示例可以正常工作。
  2. 问题是您要求用户首先输入是否要添加帐户,然后您希望第二个输入是帐户名称,但是您不向用户打印任何内容,请尝试使用代码:

num = 0 #<--Generic counting variable
names = [] # Collection for names

loop do
  print ("\nWould you like to add an account? [1 - yes] [2 - no]: > ")
  varr = gets.chomp.to_i
  break if varr == 2

  puts "Enter name"
  names[num] = gets.chomp
  puts ("The account name is #{names[num]}.")

  num += 1
end
于 2013-10-17T00:48:34.227 回答