I am trying to build a very very simple computer module that allows you to create files, view them, and edit them. I am having trouble with undefined methods and the exact nature of instance variables. I will get to those later. You can tl;dr and just go to the bolded areas.
class Computer
@@users = Hash.new
def initialize(username, password)
@username = username
@password = password
@files = Hash.new
@files["Groceries.txt"] = "10:20"
@files["Blane.txt"] = "10:30"
@@users[username] = password
end
def create(filename)
time = Time.now
@files[filename] = time
puts "A new file, #{filename}, was created at #{time}"
end
def Computer.get_users
return @@users
end
end
So I am just defining my class variable "Computer" here.
puts "You need to login!"
puts "Username?"
userName = gets.chomp.downcase
puts "Password?"
passWord = gets.chomp
my_computer = Computer.new(userName, passWord)
puts "You logged in with Username: #{userName}"
puts "and Password: #{passWord}"
puts "What would you like to do?"
puts "-- Create a file (type create)"
puts "-- Change a file (type change)"
puts "-- View a file (type view)"
puts "-- Delete a file (type delete)"
answer = gets.chomp.downcase
case answer
when "create"
puts "What is the name of the file?"
@create = gets.chomp.capitalize
if @files[@create].nil?
my_computer.create(@create)
else
puts "That file already exists!"
end
when "change"
puts "What is the name of the file you want to change?"
@files.each do |x, y|
puts "#{x}: #{y}"
end
@change = gets.chomp.capitalize
end
Now when I get the error "undefined method `[]' for nil:NilClass" which is referring to the line
if @files[@create].nil?
which is just checking if the new file is already in it. I don't know if this is a problem with where I am defining the variables, or if it is that they are instance variables, or what the problem is. Furthermore if I add the line:
my_computer.initialize(userName, passWord)
I get the following error: private method `initialize' called for #
My final problem is that when I try and print out the filenames that exist already with the following code
@files.each do |x, y|
puts "#{x}: #{y}"
end
I get the following error: undefined method `each' for nil:NilClass
I thought that the .each method was universal, but now it seems I have to define it in my class?
Sorry for the wall of text, but I'm very new to ruby and this is my first programming language, so I am trying to figure out the nuances of the language. Thanks in advance!