user1996569
user1996569

Reputation:

Ruby class variable

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?

Upvotes: 1

Views: 172

Answers (2)

Lucas Wiman
Lucas Wiman

Reputation: 11317

IMHO, this is one of the more frustrating things about Ruby's class system. The privacy of class variables is true even for subclasses. In any case, the immediate solution to your problem is to add a class method like so:

class Worker
  def self.latest
    @@latest
  end
end

Upvotes: 1

Craig Taub
Craig Taub

Reputation: 4179

The Class variables are private inside this class which is causing a problem. Therefore accessing the Worker.latest variable will cause an error as it isn't visible from instances outside of the class (but it is created and set).

Additionally, attributes are part of the object not the class so you shouldn't have an attribute for this class . In native Ruby the class variables are not accessible from outside EXCEPT through a class method (there are extensions in Rails for them tho).

Hope that helps

Upvotes: 2

Related Questions