Virtual Computer


So I was looking at the code and I was wondering, when I type, " my_computer ="Cary", 123) " how does it know to expect two arguments? The two arguments look like they were related to the initialize method and not necessarily to the Computer class in particular. And further, there is another method called create that has one parameter. If initialize and create are both methods under Computer, both with different parameters, then when I call a new variable from the Computer class why do I need to enter in two arguments for initialize but not one for create?

Here is my code for reference:

class Computer
@@users = {}
def Computer.get_users
return @@users

def initialize(username, password)
    @username = username
    @password = password
    @files = {}
    @@users[username] = password
def create(filename)
    time =
    @files[filename] = time
    puts "The file, #{filename}, was created at #{time}"


my_computer ="Cary", 123)


new is tied to initialize(). Ruby knows how many arguments are required by the number of parameters for this method.

test ="Test")     #  wrong number of arguments (1 for 2)

The create method takes a direct parameter in method calls. filename is not an instance variable, but a local one scoped to the method with its value passed in. This line uses two local variables and an instance variable:

puts "#{filename} was created by #{@username} at #{time}."

Here is an example of the create method call:

my_computer ="Roy","PassWord")

new_file.txt was created by Roy at 2015-12-18 02:19:40 +0000.


Extra for Exercise 8 (no SCT)

A simple instance utility to list user files:

  def files
      puts "Files for user #{@username} (#{@files.count})"
      @files.each { |k,v| puts "#{k} : #{v}" }
      return                     # prevent implicit return

Now we create a few files...


# and list them


new_file.txt was created by Roy at 2015-12-18 02:52:08 +0000.
newer_file.txt was created by Roy at 2015-12-18 02:52:08 +0000.
newest_file.txt was created by Roy at 2015-12-18 02:52:08 +0000.
Files for user Roy (3)
new_file.txt : 2015-12-18 02:52:08 +0000
newer_file.txt : 2015-12-18 02:52:08 +0000
newest_file.txt : 2015-12-18 02:52:08 +0000


Yet again, you come in to save the day, Roy. Thank you for your thorough answers and care in explaining these concepts to me! I had no idea that initialize was a recognized command to create an instance of a class. I thought the lessons were just using initialize as a nickname for a method.