3

水晶中的获取功能不等待用户输入。当我启动控制台应用程序时,它会立即输出如下错误。就是说给 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 语句。

4

1 回答 1

6

一些东西:

  1. 您看到的错误是编译错误。这意味着您的程序没有运行,它无法编译。
  2. gets可以返回nil(如文档中所示),例如,如果用户按下 Ctrl+C,则您必须处理此问题。如果您不关心这种情况,您可以这样做if name = gets,使用,或者使用相当于gets.not_nil!read_linegets.not_nil!
  3. Array 有一种方法includes?可以执行您尝试实现的操作
于 2016-10-11T19:51:27.603 回答