Why can't I call the create method like this?


#1

Why is this wrong to put my_computer = Computer.create(“text”) at the end?
I’d like to just print the text!

Error:
undefined method `create’ for Context::computer:Class
but… the method create is there?

class Computer

  @@users = {}
def initialize(username, password)
  @username = username
  @password = password
  @files = {}
  @@users[username] = password
  
end
  
  def create(filename)
    time = Time.now
    @files[filename] = time
 puts "#{filename} was created by #{@username} at #{time}."

  end
  def Computer.get_users
    return @@users
  end
 
end

my_computer = Computer.create("text.txt")
puts my_computer

#2

create is is a instance method, so you would first need an instance and then call the method:

my_computer = Computer.new('username', 'password')
my_computer.create("text.txt")

my_computer is the instance, now we can call the method

or you would have to convert the method to a class method, so you can call the method on class (Computer), see example:

http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

however, create becoming a class method is problematic, how does it know #{@username} then?


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.