2011-07-07 22 views
1

我想讓這個類初始化以接收要保存的消息併爲其輸入文件名。我是否正在繪製一個錯誤,因爲Ruby只需要在init方法中實例化值?溫柔,我是新手。 Traceback粘貼在下面。Ruby Class,我懷疑我正在做實例標記錯誤

class DobbsyKretts 
    idea = 'arbitaryvalue' 
    def initialize 
    #Receive idea 
    puts "Enter an idea, a secret or anything else you want to encrypt. Hit enter to stop typing and save the file" 
    @idea.gets.reverse.upcase 
    #Filename and saving - to encrypt the file. 
    puts "Enter the file name you'd like to have this saved as. Type PLAN at the beginning for plans and REM for reminders" 
    @file_name.gets.strip 
    File::open("DobbsyKrett-"+ file_name + ".txt", "w") do |f| 
     f>>@idea 
    end 
    end 
end 

something = DobbsyKretts.new 

回溯:

testy.rb:11:in `initialize': private method `gets' called for nil:NilClass (NoMethodError) 
    from testy.rb:21:in `new' 
    from testy.rb:21:in `<main>' 
Enter an idea, a secret or anything else you want to encrypt. Hit enter to stop typing and save the file 
+0

什麼是「實例標記」? –

回答

2

所分配的值之前,您正在呼籲@ideagets - 這就是爲什麼你的錯誤的原因之一。另外,不應該在這裏調用實例變量。試着這樣說:

class DobbsyKretts 
    def initialize 
    #Receive idea 
    puts "Enter an idea, a secret or anything else you want to encrypt. Hit enter to stop typing and save the file" 
    (@idea = gets).reverse.upcase 
    #Filename and saving - to encrypt the file. 
    puts "Enter the file name you'd like to have this saved as. Type PLAN at the beginning for plans and REM for reminders" 
    @file_name = gets.strip 
    File::open("DobbsyKrett-"+ @file_name + ".txt", "w") do |f| 
     f << @idea 
    end 
    end 
end 

something = DobbsyKretts.new 

這個工作您預期的那樣,但我只是想提醒你,這是一個非常糟糕的主意,做這樣的事情在構造函數中。您應該使用專用的方法來生成文件和/或詢問用戶輸入。

+0

你說get不應該在這裏調用實例變量...爲什麼?你不是在第六行添加圓括號嗎? – HareKrishna

+0

不錯,但是,謝謝。 – HareKrishna

+0

不客氣!我把gets作爲一個全局函數,它不是someobject.gets,就像你的例子。全局調用可確保從$ stdin讀取輸入。但是,您可以調用IO的實例(例如文件)。 – emboss

2

gets要麼是Kernel#getsIO#gets(我將省略ARGF#gets爲簡潔起見),@idea你的情況是不是一個IO對象(默認情況下,任何實例變量設置爲nil),並調用Kernel#gets有明確的接收器被禁止。所以正確的代碼是@idea = gets

+0

我沒有聲望投票了,所以謝謝你。 – HareKrishna

+0

@Hare:我替你替代,也指出了類實例變量。 – emboss