Crystal函数不等待用户输入

DB9*_*B93 3 crystal-lang

晶体中的获取功能不等待用户输入.当我启动我的控制台应用程序时,它立即输出如下所示的错误.这是说给in_array函数的第二个参数是Nil,但程序甚至不要求用户输入.

在此输入图像描述

我的代码如下所示.

# Only alice and bob are greeted.
def in_array(array : Array, contains : String)
    array.each { |e|
        if e == contains
            return true;
        end
    }

    return false;
end

allowed = ["Alice", "Bob"]

puts "Please enter your name to gain access."
name = gets

isAllowed = in_array(allowed, name)

if isAllowed
    puts "You can enter the secret room"
else
    puts "You are not allowed to enter the secret room."
end
Run Code Online (Sandbox Code Playgroud)

我的代码的新版本包括?和read_line

# Only alice and bob are greeted.
allowed = ["Alice", "Bob"]

puts "Please enter your name to gain access."

name = read_line.chomp

if allowed.includes?(name)
    puts "You can enter the secret room"
else
    puts "You are not allowed to enter the secret room."
end
Run Code Online (Sandbox Code Playgroud)

但是当我将Bob输入名称变量时,包括?method返回false并执行else语句.

ast*_*ite 6

一些东西:

  1. 您看到的错误是编译错误.这意味着您的程序未运行,无法编译.
  2. gets可以返回nil(如文档中所示),例如,如果用户按下Ctrl + C,则必须处理此问题.您可以这样做if name = gets,gets.not_nil!如果您不关心这种情况,可以使用,或使用read_line相同的gets.not_nil!
  3. Array有一个方法includes?可以执行您要实现的操作

  • `gets`和`read_line`包含尾随换行符,你需要调用`chomp`来删除它 (3认同)