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
You are calling
getson@ideabefore 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.