不能在Ruby中使用split

use*_*856 0 ruby

我试图split在Ruby中使用,但我收到此错误:

`importantFuncs':私有方法`split'调用nil:NilClass(NoMethodError)

我曾尝试加入require Stringrequire string,但也都在工作.

require 'socket'
class IRC
    def initialize(ip, port)
        @s = TCPSocket.new(ip, port)
        print 'Now connected to ip ', ip, ' at port ', port, "\n"
    end
    def getPacket()
        line = @s.gets
        puts line
    end
    def closeConnection()
        @s.close
    end
    def sendPacket(packet)
        @s.write(packet)
    end
    def importantFuncs(nick)
        sendPacket("NICK #{nick}")
        z = getPacket
        @m = z.split(':')
        sendPacket("NICK #{nick}")
    end
    #def joinChannel(
end
ip = '127.0.0.1'
port = '6667'
i = IRC.new(ip, port)
i.importantFuncs('test')
i.getPacket
Run Code Online (Sandbox Code Playgroud)

Fle*_*oid 6

您的getPacket方法返回nil而不是字符串line.

那是因为在Ruby中,每个方法都默认返回一个值.此值将是方法中最后一个语句的值.您也可以使用returnstatement来重新定义此行为,就像在其他编程语言中一样,但它在Ruby中并不经常使用.

def getPacket()
  line = @s.gets
  puts line # returns nil, and whole method returns nil too
end
Run Code Online (Sandbox Code Playgroud)

因此,您应该@s.gets在此方法中创建最后一个表达式

def getPacket()
  @s.gets
end
Run Code Online (Sandbox Code Playgroud)

line如果你真的需要打印这个,请添加到最后line

def getPacket()
  line = @s.gets
  puts line
  line
end
Run Code Online (Sandbox Code Playgroud)