如何在ruby中的类中访问Object?

时间:2012-11-03 17:07:29

标签: ruby

我尝试了以下内容:

require "socket"

class IRC
def initialize(server, port=6667, user='ruby-bot')
    @server = server
    @port = port
    @user = user
end

def connect!
    @s = TCPSocket.open(@server, @port) #connect
    raise "Couldn't connect to #{@server}:#{@port}" unless @s #error handling
    @s.puts "USER #{@user} +B :IRC Ruby Bot" #set modes etc
end 

def nick(nick=nil)
    @s.puts "NICK #{@nick}"
end

def join(channel)
    @s.puts "JOIN #{channel}"
end
end

然后:

#!/usr/bin/ruby
require './irc.rb'

print 'Server: '
server = gets
print 'Port (6667): '
port = gets

if port.match(/^\n/)
port = '6667'
end

bot = IRC.new(server, port)
bot.nick 'fbot1830'
bot.join '#myowntestchannel'

我收到以下错误:

./irc.rb:17:in `nick': private method `puts' called for nil:NilClass (NoMethodError) from ./bot.rb:14

这是我第一次尝试在ruby中编写自定义类,请耐心等待,我希望我的错误不是太微不足道;)

1 个答案:

答案 0 :(得分:7)

@s已在connect!方法中初始化,但该方法永远不会被调用,因此@s会在nil方法中评估为nick