水晶函数不等待用户输入

3
在 Crystal 中,gets 函数不会等待用户输入。当我启动控制台应用程序时,它会立即输出以下类似的错误。它说给 in_array 函数的第二个参数是 Nil,但程序甚至没有要求用户输入。

enter image description here

我的代码如下。

# 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 语句。
1个回答

6

需要注意以下几点:

  1. 你看到的错误是一个编译错误,这意味着你的程序无法运行,它未能通过编译。
  2. gets 可以返回 nil(在文档中有说明),例如如果用户按下 Ctrl + C,则必须处理此情况。你可以使用 if name = gets 、使用 gets.not_nil! (如果你不关心此情况)或者使用等价于 gets.not_nil!read_line
  3. Array 有一个方法叫做 includes? ,它就是你试图实现的功能。

  1. 当编译器检测到错误时,它将停止编译,您需要修复错误,这对我现在很清楚了。
  2. 我将gets函数更改为read_line,我使用puts命令显示了变量名,并显示了我输入的名称。
  3. 是的,in_array函数与includes完全相同吗?我现在已经更改了它,但它仍然无法正常工作,因为当我输入允许数组中的名称Bob时,它会显示false,然后执行else语句。我已更新我的代码为新版本。
- DB93
3
gets和read_line包含结尾的换行符,需要调用chomp函数来删除它。 - asterite

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接