2012-11-03 20 views
-1

我試過如下:如何在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 

這是寫在紅寶石的自定義類我第一次嘗試,請耐心等待,我希望我的錯誤不是太瑣碎;)

回答

7

@sconnect!方法中被初始化,但該方法從未被調用,因此@snick方法中評估爲nil

+0

哈哈thx,我是個白癡;) –

相關問題