Class as a Hash Value

I’m new to ruby and I’m trying to understand how can I access the
methods of a class I created, if I have an Hash and their values are
that class.

class User

@username
@password
@name
@balance

def initialize
@username = nil
@password = nil
@name = nil
@balance = nil
end

def getUsername
@username
end

… rest of getters and setters …
#method to create a new user
def createUser
puts “Insert (username:password:name:balance):”
var = gets.chomp
array = var.split(":")
@username = array[0]
@password = array[1]
@name = array[2]
@balance = array[3].to_f
end

def readUser
puts “Username :: #{@username}”
puts “Name :: #{@name}”
puts “Balance :: #{@balance}”
end

end

require_relative ‘user’
class House
@users

def initialize
@users = Hash.new
end

#users interface
def registerUser
newUser = User.new
newUser.createUser
@users[newUser.getUsername] = newUser

end

def viewUsers
@users.each do |key|
@users[key].readUser
end
end
end

The problem it’s in the viewUsers function. I can’t access readUser
function from User class.

Error:
“in block in viewUsers': undefined methodreadUser’ for User:Class
(NoMethodError)”

Can anyone help me?
How can I resolve this?

It should be

@users.each_key

and not

@users.each

Even simpler:

@users.values { |u| u.readUser }

No need to use the keys here.

Thank you Ronald. It worked.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs