Ruby 类,我怀疑我做错了实例标记
我希望此类初始化以接收要保存的消息并为其输入文件名。我是否因为 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
I want this class to initialize to receive a message to be saved and enter a filename for it. Am I drawing up an error because Ruby only wants values to be instantiated in the init method? Be gentle, I'm new to this. Traceback pasted below.
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
Traceback:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在分配值之前对
@idea
调用gets
- 这是您收到错误的原因之一。另外,不应在此处对实例变量调用 gets。像这样尝试一下:这正如您所期望的那样工作,但我只是想提醒您,在构造函数中执行类似的操作是一个非常糟糕的主意。您应该使用专用方法来生成文件和/或要求用户输入。
You are calling
gets
on@idea
before having assigned a value - that's one of the reasons why you get the error. Also, gets should not be called on the instance variable here. Try it like this:This works as you expected, but I just would like to remind you that it is a very bad idea to do something like this in the constructor. You should rather use a dedicated method for generating files and/or asking the user for input.
gets
是Kernel#gets
或IO#gets
(为简洁起见,我将省略ARGF#gets
),在您的情况下,@idea
不是 IO 对象(默认情况下,任何实例变量都设置为nil
),并且显式调用Kernel#gets
接收者被禁止。所以正确的代码是@idea = gets
。gets
is either aKernel#gets
orIO#gets
(I will omitARGF#gets
for brevity),@idea
in your case is not an IO object (by default any instance variable is set tonil
), and callingKernel#gets
with explicit receiver is prohibited. So correct code is@idea = gets
.