水晶中的获取功能不等待用户输入。当我启动控制台应用程序时,它会立即输出如下错误。就是说给 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
我的代码的新版本使用包含?和 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 输入到 name 变量中时,包括?方法返回 false 并执行 else 语句。