开发者

Debugging simple Ruby class method?

开发者 https://www.devze.com 2023-03-19 02:16 出处:网络
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\"
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 yo开发者_如何学Pythonu'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


The function gets will return a string with the line-ending character at the end which is not what you expected. To remove it, use the chomp function:

@response = gets.chomp

It is okay for a method (e.g. unzip) to create new instance variables (e.g. @valueholder). In general it's always better for your variables to have the smallest possible scope, so unless you need to read valueholder later, you should just use a local variable (remove the @ from the name):

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

Also, valueholder is a terrible name for a variable but if you made it a local variable that could be excused.

Also, your block startings/endings are mismatched. Here's a fixed version of your function that shouldn't result in syntax errors:

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

Edit: You should capitalize File to correctly call File.read.

0

精彩评论

暂无评论...
验证码 换一张
取 消