Virtual Computer


#1

So I was looking at the code and I was wondering, when I type, " my_computer = Computer.new("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
end

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

end

my_computer = Computer.new("Cary", 123)


#2

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

test = Computer.new("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 = Computer.new("Roy","PassWord")
my_computer.create("new_file.txt")

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

#3

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
  end

Now we create a few files...

my_computer.create("new_file.txt")
my_computer.create("newer_file.txt")
my_computer.create("newest_file.txt")

# and list them

my_computer.files

=begin
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
nil 
=end

#4

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.