2011-07-07 45 views
-2
class DobbsyKretts 
    def initialize 
    #Receive idea 
    puts "Enter an idea, a secret or anything else you want to secretize; 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.chomp.upcase) 
    File::open("DobbsyKrett-"+ @file_name + ".txt", "w") do |f| 
     f << @idea 
    end 
    end 

    def unzip 
    puts "Do you want to withdraw PLAN or REM" 
    response = gets.chomp.upcase! 
    puts "Invalid" if !["PLAN","REM"].include?(response) 
    file_contents = nil 
    Dir['DobbsyKrett-'+response+"*.txt"].each do |file_nom| 
     file_contents = File.read(file_nom) 
    end 
    puts file_contents 
    end 
end 
somethingsomething1 = DobbsyKretts.new 
somethingsomething1.unzip 


    def unzip 
    puts "Do you want to withdraw PLAN or REM" 
    @response = gets.strip 
    if @response.downcase != "plan" and @response.downcase != "rem" 
     puts "Invalid" end 
    Dir["DobbsyKrett-"[email protected]+".txt"].each do |file_nom| 
     @value = file.read(file_nom) 
    end 
    puts @value 
    end 
end 
+1

http://sscce.org/ –

回答

0

函數gets將在結尾處返回一個字符串,其行結束字符與您的預期不符。要刪除它,使用格格功能:

@response = gets.chomp 

這是正常的方法(例如unzip)來創建新的實例變量(例如@valueholder)。一般來說它總是爲你的變量最好有儘可能小的範圍內,所以,除非你需要稍後閱讀valueholder,你應該只使用一個局部變量(從名稱中刪除@):

Dir["DobbsyKrett-"[email protected]+".txt"].each do |file_nom| 
    valueholder = File.read(file_nom) 
end 
puts valueholder 

而且,valueholder對於一個變量來說是一個可怕的名字,但是如果你把它變成了一個可以原諒的局部變量。

此外,您的塊啓動/結尾不匹配。這是你的函數的一個固定的版本,不應該導致語法錯誤:

def unzip 
    puts "Do you want to withdraw PLAN or REM" 
    response = gets.chomp.downcase 
    if !["plan","rem"].include? response 
    puts "Invalid" 
    else 
    Dir["DobbsyKrett-#{response}.txt"].each do |file_nom| 
     valueholder = file.read(file_nom) 
    end 
    puts valueholder 
    end 
end 

編輯:你應該利用File能正確調用File.read

+0

然後@response會發生什麼? Ruby如何知道您是指在DIR行中使用PLAN還是REM? – HareKrishna

+0

對不起,我的錯誤...我會糾正我的回答 –

+0

謝謝...代碼的最後一行(看我的,我更新)應該打印所有的DobbsyKrett-PLAN ...文件或所有的DobbsyKrett- REM ...文件。但是我只有在創造我的課程時才支持我創造的任何東西。爲什麼是這樣? – HareKrishna