我希望这个类初始化为接收要保存的消息并为其输入文件名。我绘制了一个错误,因为Ruby只希望值在init方法中实例化?温柔点,我是新手。追溯粘贴在下面。
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
在分配值之前,您正在@idea
上调用gets
-这是您获得错误的原因之一。另外,不应该在实例变量上调用get。试试这样:
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
这是您所期望的,但我只是想提醒您,在构造函数中做这样的事情是一个非常糟糕的主意。您应该使用专门的方法来生成文件和/或请求用户输入。
gets
是Kernel#gets
或IO#gets
(为了简洁,我将省略ARGF#gets
), @idea
在您的情况下不是IO对象(默认情况下任何实例变量都设置为nil
),并且禁止使用显式接收器调用Kernel#gets
。所以正确的代码是@idea = gets