Crystal 函数不等待用户输入
Crystal function gets not waiting for user input
crystal 中的获取函数未等待用户输入。当我启动我的控制台应用程序时,它会立即输出如下所示的错误。它说给 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 输入到名称变量中时,包括?方法 returns false 并执行 else 语句。
几件事:
- 您看到的错误是编译错误。这意味着你的程序不是运行,编译失败
gets
可以returnnil
(如docs所示),例如如果用户按下Ctrl+C,那么你必须处理这个。如果您不关心这种情况,您可以使用 if name = gets
,使用 gets.not_nil!
,或者使用等同于 gets.not_nil!
的 read_line
- Array 有一个方法
includes?
可以执行您要实现的操作
crystal 中的获取函数未等待用户输入。当我启动我的控制台应用程序时,它会立即输出如下所示的错误。它说给 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 输入到名称变量中时,包括?方法 returns false 并执行 else 语句。
几件事:
- 您看到的错误是编译错误。这意味着你的程序不是运行,编译失败
gets
可以returnnil
(如docs所示),例如如果用户按下Ctrl+C,那么你必须处理这个。如果您不关心这种情况,您可以使用if name = gets
,使用gets.not_nil!
,或者使用等同于gets.not_nil!
的 - Array 有一个方法
includes?
可以执行您要实现的操作
read_line