我正在尝试通过阅读有关类变量的教程来学习 Ruby。
该代码创建了一个“Worker”对象,创建了一个类变量来跟踪用户最后创建的 Worker 实例。
我从作者那里复制了代码,但我得到了错误:
undefined method `latest' for Worker:Class (NoMethodError)
我找到的代码是:
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
有人能看出为什么吗?