Newbie uninitialized constant question

Hi, I’m pretty new to Ruby and I can’t figure out how to fix the
following error message in the project I just started. I’ve figured out
what I did wrong on the my_list.add line but haven’t been able to fix it
and have spent a decent amount of time on it so any help would be
appreciated. Thanks

error:‘class:List’: uninitialized constant List::Task

code:
class List
attr_reader :all_tasks

if FILE == $PROGRAM_NAME
my_list = List.new
puts “You’ve made a new list”
puts “What task do you want to add?”
user_input = gets.chomp
my_list.add(Task.new (user_input))
puts “You have added #{user_input} to the ToDo list”
end

def initialize
@all_tasks = []
end

def add(task)
all_tasks << task
end
end

class Task
attr_reader :desc

def initialize(desc)
@desc = desc
end
end

Brian Booth wrote in post #1183383:

error:‘class:List’: uninitialized constant List::Task

code:
class List
attr_reader :all_tasks

if FILE == $PROGRAM_NAME

my_list.add(Task.new (user_input))

end

end

In the ‘if FILE…’ , you ask class analyser to execute code
immediately, so Task class is unknown a this moment.

A class is a constant, so ‘uninitialized constant’ mean unknown
class…

Move the ‘if FILE…’ code at the end of the script,
and this should work!

It worked! Thank you!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs