Access a hash / list in a class

0

Hello.

I'm an intermediate student in python, and recently I started studying Ruby, but like every new language, comes a few minor difficulties.

My question is: Where is the error in this? I used the has_key?() function outside of the class, and it worked perfectly, but within the class, it gives the following error:

'FuncLogin': undefined method 'has_key?' for nil:NilClass (NoMethodError)

I'm doing a simple login and account creation program, but it's giving this error. Here is the complete code:

class User
attr_accessor :login, :password

@contas = {"admin" => "pass"}

def initialize(login, password)
    @login    = login
    @password = password
end

def FuncLogin
    if @contas.has_key?(@login)
        if contas[@login] == @password
            return "Logado"
        else
            puts "Senha incorreta."
        end
    else
        return "Login inexistente."
    end
end
end
    
asked by anonymous 13.11.2018 / 02:27

1 answer

1

The problem is that you assign @contas within the scope of the class. In Ruby, scopes are very important.

See the following example:

class Carro
  attr_accessor :modelo, :ano

  def andar
    puts 'Estou andando...'
  end
end

This attr_accessor is called from the class scope because there is no instance defined. The def andar , is the same case. You define a method in the class, to be accessed by object instances.

To set the value of a attr_accessor field, you should do it at the instance level.

class Carro
  attr_accessor :modelo, :ano

  def initialize(modelo, ano)
    @modelo = modelo
    @ano = ano
  end

  def andar
    puts 'Estou andando...'
  end
end

The constructor method, initialize can handle this, since it is called at the instance level.

tesla = Carro.new 'Tesla Model 3', 2018
tesla.andar

Another point: always follow the conventions. For classes / modules, use PascalCase . For variables and methods, use snake_case_minusculo . This can cause you problems later on, since in Ruby, every object declared with a capital initial, that is, Abc or ABC , is a constant.

    
15.11.2018 / 18:08