【问题标题】:private method `puts' called for nil:NilClass (NoMethodError)为 nil 调用私有方法“puts”:NilClass (NoMethodError)
【发布时间】:2014-09-28 20:04:51
【问题描述】:

当我尝试从类中的另一个方法访问实例变量时,我不确定为什么无法访问它。

该程序是一个聊天程序(正在进行中)。抱歉,如果这是一个菜鸟问题,我正试图从我已经知道的其他语言中强行学习 Ruby。

require 'socket'      # Sockets are in standard library

class Client
    def initilize()
        hostname = 'localhost'
        port = 2000
        @s = TCPSocket.open(hostname, port)   
    end

    def startChat  
        puts "Starting Client"
        message = gets.chomp
        @s.puts(message)

        while line = @s.gets   # Read lines from the socket
            puts line.chop      # And print with platform line terminator
            @s.close               # Close the socket when done
            gets.chomp
        end
    end
end

c = Client.new()

c.startChat

【问题讨论】:

  • @BorisStitnicky sigh 是的,我意识到我打开了太多的蠕虫罐头。无论如何,问题仍然是某处的nil.puts
  • 感谢您的帮助,sevenseacat 发现了错字。
  • 顺便说一句,它抱怨私有方法 puts 因为 putsKernel 中作为私有方法(以及所有其他标准的“真正的全局方法”) )。

标签: ruby variables methods instance puts


【解决方案1】:

您的def initialize() 中有错字,因此在初始化客户端实例时不会调用它。因此@s 永远不会被定义(所以它是 nil)。

【讨论】:

  • 谢谢,就是这样。我可能应该开始使用调试器了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
  • 1970-01-01
相关资源
最近更新 更多