Virtual Machine (Object Oriented Programming I) - How do I utilize the get_users class method?


#1

In the virtual machine assignment we create a class method get_users that returns @@users - How do I access this method? How would I print it to the console?


#3
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("#{@username} created #{filename} at #{time}")
  end
  
 
  def Computer.get_users
      @@users
  end
end

r0ckf0rd = Computer.new("r0ckford", "67890")
r0ckf0rd.create("text_file.txt")

james = Computer.new("jjames", "12345")
james.create("image.png")

puts "Users: #{Computer.get_users}"


=> r0ckford created text_file.txt at 2018-10-09 18:12:05 +0000
=> jjames created image.png at 2018-10-09 18:12:05 +0000
=> undefined method `get_users' for Context::Computer:Class


#5

it seems there are 3 ways to declare class methods:

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

your approach seems closest to option3, only this approach means that the class method should be defined outside/after the class.