在 Crystal 中,gets 函数不会等待用户输入。当我启动控制台应用程序时,它会立即输出以下类似的错误。它说给 in_array 函数的第二个参数是 Nil,但程序甚至没有要求用户输入。
使用includes?和read_line的我的代码的新版本。
但是当我将“Bob”输入到名称变量中时,includes? 方法返回 false 并执行 else 语句。
我的代码如下。
# 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
使用includes?和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
但是当我将“Bob”输入到名称变量中时,includes? 方法返回 false 并执行 else 语句。