调试简单的Ruby类方法?

时间:2011-07-07 14:06:06

标签: ruby debugging class instance-variables

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-"+@response+".txt"].each do |file_nom|
      @value = file.read(file_nom)
    end
    puts @value
  end
end

1 个答案:

答案 0 :(得分:0)

函数gets将返回一个字符串,其末尾的行结尾字符不是您所期望的。要删除它,请使用chomp函数:

@response = gets.chomp

方法(例如unzip)可以创建新的实例变量(例如@valueholder)。一般来说,变量最好具有尽可能小的范围,因此除非您需要稍后阅读valueholder,否则您应该只使用局部变量(从名称中删除@):

Dir["DobbsyKrett-"+@response+".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