Search code examples
rubynomethoderror

Undefined method for class / calling methods outside of a class


class Computer_create

  public
  def initialize(filename)
    @@files = []
    @filename = filename
  end

  public
  def create(filename)
    @@files << filename
    puts "File: #{filename} has been created"
  end

  public
  def list
    return @@files
  end
end

file_1 = Computer_create.new("FileTest")
file_1.create("FileTest")

Computer_create.list

im just trying to make a simple sort of database which can make files, and store them in a Array, working on storing them in a hash though. But every time i try out my code it gives me this:

"computer_create.rb:24:in <top (required)>': undefined methodlist' for Computer_create:Class (NoMethodError)"

what im trying to do is: make a file called FileTest via file_1 and then list all the files in @@files but it just doesnt seem to work.


Solution

  • The error message is exactly right; the class doesn't have a list method.

    Call list on the instance of Computer_create you already created, e.g.,

    file_1.list
    

    In other words, exactly how you called the other instance method, file_1.create.

    You're also using @@ in an... unusual way. As far as I can tell you mean those variables to be instance variables, which require only a single @.

    Unrelated, but putting public before each public method is noisy and unnecessary. In fact, I'd say only put private, once, in front of a collection of private methods.