I am trying to learn Ruby by reading tutorials on Class Variables.
The code creates a "Worker" object, a class variable is created to keep track of which instance of Worker was created by the user last.
I have copied the code from the author but I get the error:
undefined method `latest' for Worker:Class (NoMethodError)
The code I have found is:
class Worker
attr_writer :number_of_jobs
def initialize(name, job)
@name = name
@job = job
@@latest = @name
@@job = @job
puts "Lets get started"
end
def new_job(job)
@job = job
puts "I moved to #{job}!"
self.fetch_info
end
def name_update(name_new)
@name = name_new
puts "My new name is #{name_new}."
self.fetch_info
end
def fetch_info
puts "I'm #{@name} in #{@location}."
end
def job_score
return "#{@number_of_jobs * 10}Fg"
end
protected
def are_you_worker?(guest_name)
puts "Yes #{guest_name}, I am a worker!"
return true
end
private
def text_a_message(message)
puts message
end
public
def tell_friend(where)
text_a_message("I just applied to #{where}")
end
end
#running the code
Worker1 = Worker.new("Steve", "Support")
Worker2 = Worker.new("Alan", "PA")
puts Worker.latest
Can anybody see why?
Worker.latest: you send thelatestmessage to the Worker class. All you need to respond to this message is a singleton method (aka class method) defined in Worker or its hierarchy, as RecursivelyIronic answered. And the name of the method has nothing to do with the name of the variable you want to access. It is of course preferable for the understanding that thelatestmethod answers@@latestrather than @@job or the name of the Worker.