Ruby'is_a?' 需要的类或模块(TypeError)

Mar*_* Jr 20 ruby conditional integer typeerror while-loop

我正在玩Ruby并尝试创建一个小银行帐户程序.当我运行使用create_account运行的特定代码行时:

unless @response.is_a? Integer && @response.to_str.length == 4
    puts "Your response must be 4 numbers in length."
    create_account
else
    @pin = @response
    puts "Your pin has been set."
end
Run Code Online (Sandbox Code Playgroud)

我收到了这个回复:

bank_account.rb:24:in 'is_a?':class or module required (TypeError)
    from bank_account.rb:24:in 'create_account'
    from bank_account.rb:47:in '<main>'
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚发生了什么,但我包括了其余的代码.这是不完整的,显然是因为我坚持这一部分.我经历一个while循环并输入'Create Account'来启动create_account方法.我的目标是运行条件并要求用户键入一个4位整数,就像任何ole pin号一样.如果它不是整数,也不是4位数,我调用create_account方法让它们重新开始.

如果有必要,我正在运行ruby 2.0.0,但我打赌它可能更多地与我的代码有关.Stackoverflow对我来说是新的,所以如果有人提出这个问题我很抱歉.在提出问题之前,我按照建议做了我的作业,但我仍然难过.任何帮助表示赞赏.

小智 51

你需要将类Integer放在括号中:

unless @response.is_a?(Integer) && @response.to_str.length == 4
Run Code Online (Sandbox Code Playgroud)

你实际上evaulating is_a?(Integer && @response.to_str.length == 4)这是一个布尔值,而不是一个类或模块.